0
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 原型在 method2().init() 函数运行返回未定义?

有没有原型的替代品?谢谢你。

4

3 回答 3

1

该问题与this绑定init函数的不同范围有关method2(),因此请尝试以下操作:

this.method2 = function() {
    var self = this;      
    return {
        init: function() { return self.public; }
    }
};

所以

object.method2().init(); // return "method prototype"
于 2012-10-02T10:29:48.487 回答
1

这有很多问题。

但是对您的具体问题的直接答案是调用init返回 undefined 因为它对this您创建的内部对象的引用而不是您认为它引用的实例。

我建议你停止尝试解决这个特殊问题,并学习 JavaScript 中原型继承的基础知识

于 2012-10-02T10:30:41.777 回答
0

函数中的 this 是返回的对象this,它没有任何属性。initobject.method2()public

于 2012-10-02T10:30:02.607 回答