Properties of Javascript function objects

testndtv picture testndtv · Mar 2, 2013 · Viewed 35.2k times · Source

I have a JavaScript function object as;

var addNum = function(num1, num2) {
        return num1 + num2;
}

Now if I try to access

addNum.divide()

I wanted to understand the prototype chain for the above code. I read that in the above example, addNum would be searched for divide(), followed by Function.prototype and finally Object.prototype.

But my question is in the above example, how can addNum would be searched for divide()

Does it refer to something like ;

var addNum = function(num1, num2) {

this.divide = function(){}

            return num1 + num2;
    }

I could not understand the line where it says addNum would be searched for divide()

Please help me understand the same.

Answer

Keith Morris picture Keith Morris · Mar 2, 2013

I'm not sure this will answer your question but may give you some insight. Consider the following example:

var Person = (function () {
    var Person = function (name) {
        this.name = name;
    }

    Person.greet = function () {
        console.log("Hello!");
    }

    Person.prototype = {
        greet: function () {
            console.log('Hello, my name is ' + this.name);
        }
    };
    return Person;
})();

var bob = new Person("Bob");

Person.greet(); // logs "Hello!"
bob.greet(); // logs "Hello, my name is Bob

The function object "Person" has a direct 'greet' property that is a Function. OOP-wise, you can almost think of that as a static method that can be called directly from the Person Function (Person.greet()). Once you "instantiate" a person object from the Person constructor, that new object "bob" now references it's methods from the Person.prototype object. Now when you call bob.greet(), it uses the greet function in the prototype object.

Hope that helps.