var fn = function() {
this.method1 = function() {
return this.public;
};
this.method2 = function() {
return {
init: function() { return this.public; }
}
};
fn.prototype.public = "method prototype";
};创建对象fn
var object = new fn();
object.method1() // "method prototype"
object.method2().init(); // undefined this.public Prototype in method2().init()函数运行返回未定义?
有没有原型的替代方案?谢谢。
发布于 2012-10-02 18:29:48
这个问题与this绑定在method2()的init函数上的作用域不同有关,所以可以尝试这样做:
this.method2 = function() {
var self = this;
return {
init: function() { return self.public; }
}
};所以
object.method2().init(); // return "method prototype"发布于 2012-10-02 18:30:42
这里面有很多错误。
但对您的特定问题的直接回答是,调用init会返回未定义的结果,因为它对this的引用是对您创建的内部对象的引用,而不是您认为它引用的实例。
我建议您停止尝试解决这个特定的问题,并学习JavaScript中原型继承的基础知识
发布于 2012-10-02 18:30:03
init函数中的此this是由object.method2()返回的对象,它没有public属性。
https://stackoverflow.com/questions/12688593
复制相似问题