Javascript OOP prototype.method调用this.method
创建对象fnJavascript OOP prototype.method调用this.method,javascript,Javascript,创建对象fn var fn = function() { this.method1 = function() { return this.public; }; this.method2 = function() { return { init: function() { return this.public; } } }; fn.prototype.public =
var fn = function() {
this.method1 = function() {
return this.public;
};
this.method2 = function() {
return {
init: function() { return this.public; }
}
};
fn.prototype.public = "method prototype";
};
method2()中的this.public原型。init()函数运行返回未定义
有原型的替代品吗?
谢谢。此问题与
此
绑定到method2()
的init
函数的不同范围有关,请尝试以下操作:
var object = new fn();
object.method1() // "method prototype"
object.method2().init(); // undefined
所以
init
函数中的This
是object.method2()
返回的对象,它没有public
属性。这有很多错误
但是对您的具体问题的直接回答是调用init
返回未定义,因为它对this
的引用是您创建的内部对象,而不是您认为它引用的实例
我建议您停止尝试解决这个特定的问题,学习JavaScript中原型继承的基础知识。此外,我知道这只是示例代码,但
public
在JavaScript中是一个保留关键字,即使它实际上没有被使用。避免使用保留字作为标识为什么-1?刚才问你一个问题?
this.method2 = function() {
var self = this;
return {
init: function() { return self.public; }
}
};
object.method2().init(); // return "method prototype"