কম্পিউটার টিউটোরিয়াল

জাভাস্ক্রিপ্টে মেথড কীভাবে ডিফাইন করবেন?


মেথড ডেফিনিশন

জাভাস্ক্রিপ্টে একটি মেথড হলো অবজেক্টের ওপর করা একটি অ্যাকশন। একটি জাভাস্ক্রিপ্ট মেথডের একটি ফাংশন ডেফিনিশন থাকে যা প্রোপার্টি ভ্যালু হিসেবে সংরক্ষিত হয়।

উদাহরণ

<!DOCTYPE html>
<html>
    <body>
        <h3 id="myDept"></h3>
        <script>
            var department = {
                deptName: "Marketing",
                deptID: 101,
                deptZone: "North",
                details: function() {
                    return "Department Details<br>" + 
                           "Name: " + this.deptName + " <br>" +
                           "Zone: " + this.deptZone + "<br>" +
                           "ID: " + this.deptID;
                }
            };
            
            document.getElementById("myDept").innerHTML = department.details();
        </script>
    </body>
</html>

আধুনিক মেথড সিনট্যাক্স (ES6+)

const department = {
    deptName: "Marketing",
    deptID: 101,
    deptZone: "North",
    
    // মেথড শর্টহ্যান্ড (প্রস্তাবিত)
    details() {
        return `Department Details
Name: ${this.deptName}
Zone: ${this.deptZone}
ID: ${this.deptID}`; }, // অ্যাসিঙ্ক মেথড async fetchDetails() { const response = await fetch(`/api/dept/${this.deptID}`); return response.json(); }, // গেটার/সেটার get fullName() { return `${this.deptName} (${this.deptZone})`; } };

this বাইন্ডিং মনে রাখুন

const obj = {
    value: 42,
    method() {
        console.log(this.value); // 42
    }
};

const unbound = obj.method;
unbound(); // undefined (this লস)

// সমাধান: bind() বা অ্যারো ফাংশন
const bound = obj.method.bind(obj);
bound(); // 42
  1. জাভাস্ক্রিপ্ট exec() মেথড

  2. জাভাস্ক্রিপ্ট getTime() মেথড

  3. জাভাস্ক্রিপ্ট Sort() মেথড

  4. জাভাস্ক্রিপ্ট কনস্ট্রাক্টরে প্রপার্টি এবং মেথড যোগ করার পদ্ধতি