原型中对'this'的引用不起作用

时间:2017-04-26 07:47:12

标签: javascript

var MyClass = function() { 
    //some functionality goes here 
};

MyClass.prototype.xyz = function() { 
    //some functionality goes here 
};

MyClass.prototype.abc = function() {
    var self = this;
    // here self is not working and 'this.xyz()' isn't working too.
    self.xyz();
    // It works if I use MyClass.prototype.xyz();
};

有人可以帮助我在这里失踪吗?

1 个答案:

答案 0 :(得分:-1)

我真的不知道你如何在这里调用你的功能,但这很有效:

var MyClass = function() { 
    console.log("constructor");
};

MyClass.prototype.xyz = function() { 
    console.log("xyz");
};

MyClass.prototype.abc = function() {
    console.log("abc");
    this.xyz();
};

let myClass = new MyClass();

myClass.xyz();
myClass.abc();

,输出很简单:

constructor
xyz
abc
xyz