g.pickardou
g.pickardou

Reputation: 35843

Why is this Javascript prototype function called and who calls it with undefined?

Having this .js file:

var MyClass = function() {
};
MyClass.prototype = function myMethod(name) {
    // my statements here...
    // name is undefined here, but who calls this function and why?
    return {
        myMethod: myMethod
    };
}();

and a page which loads it:

<head>
    ... 
    <script src="myfile.js"></script>
</head>

Question

Why is this function called? As far as with my javascript limited knowledge I understand I am initializing a MyClass variable (which is containing a function) and adding a new function to the prototype. Obviosly I am missing something.

Upvotes: 0

Views: 128

Answers (2)

apena
apena

Reputation: 2321

Your code works as-is. myMethod is declared but because you end the declaration with () myMethod is executed on the spot and returns an object with a property pointing to itself that you cannot access, hence you get undefined. You are simply missing an important fact about Javascript Classes.

Classes must be instantiated before a prototype method written in that fashion is available to call. By calling MyClass.myMethod() (which is what I assume you are trying to do) you are trying to access the method on the Class MyClass rather than accessing the method of an instance of MyClass which is what I assume what you want. Simply create an instance of MyClass using the new keyword and myMethod will be available to you (see this MDN doc page for more information). So without changing any of your code:

var myInstance = new MyClass
myInstance.myMethod('foo') // returns an object you are looking for

Upvotes: 1

Quentin
Quentin

Reputation: 943510

It gets called because it has () after it.

The first argument is undefined because there are no values between that pair of ( and ).

You should write either

MyClass.prototype.myMethod = function myMethod(name) {
    // my statements here...
};

or

MyClass.prototype = (function(){
    function myMethod(name) {
        // my statements here...
    }
    return {
        myMethod: myMethod
    };
})();

Upvotes: 3

Related Questions