简体   繁体   中英

Why can't I call a method on the prototype?

I am trying to create a JavaScript object constructor within a closure, and then return the constructor so that I can create this object without any conflicts with other JS libraries.

Consider this code:

Test = (function(){

    var T = function(){
        this.x = 0;
    }

    T.prototype.doSomething = function(){
        this.x = 10;
    }

    return T;

});
var test = new Test();
test.doSomething(); 
alert(test.x);

Why is it that test.doSomething() is not a function, when I have defined it in the prototype?

You're not creating an instance of the right function! If you look at Test :

var Test = (function() {
  //...
  return T;
});

Here, you're assigning Test to function that returns T , not T itself! That's why you can't call a method on the prototype of T . Instead, use an IIFE:

var Test = (function() {

})(); //Important!

This will assign T 's reference to Test . Then create a new instance:

new Test();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM