【问题标题】:Properties declared *in* the Constructor are visible in instances. Why?*in* 构造函数声明的属性在实例中可见。为什么?
【发布时间】:2011-01-17 01:15:00
【问题描述】:

在 Javascript 的原型继承系统中,对象的内部原型引用设置为其构造函数的“原型”属性,该属性本身就是一个对象。

构造函数的“原型”属性的属性可以像对象实例的属性一样被解析。但是,构造函数对象的实际属性可供实例访问:

function MyConstructor() { }
MyConstructor.x = 3
MyConstructor.prototype.y = 7

a = new MyConstructor()
a.x == 3    // FALSE
a.y == 7    // TRUE

但是,如果构造函数的属性(“x”)在函数体中用this关键字声明,这些属性当然是由实例解析的:

function MyConstructor() {
    this.x = 3
}
MyConstructor.prototype.y = 7

a = new MyConstructor()
a.x == 3    // TRUE

为什么?有什么区别?

【问题讨论】:

    标签: javascript oop inheritance prototype this


    【解决方案1】:

    当你这样做时:

    MyConstructor.x = 3;
    

    ...您只向MyConstructor 引用的Function 对象实例添加了一个属性。 Function 对象有许多属性不会成为实例的一部分(您也不希望它们成为)。

    因此,通过构造函数创建实例属性的机制是使用this.x 方法。

    当构造函数运行时,this正在返回的对象。所以这只是一种方便,所以你不必这样做:

    a = new MyConstructor();
    a.x = 3;
    a.x == 3    // TRUE!
    

    由于构造函数中的this 与生成的对象相同,因此无需在每次创建新实例时显式执行此操作。

    prototype 对象只是一个被MyConstructor 的所有实例引用的对象,因此如果该实例上没有属性,则它会转到prototype 来查找。


    为了说明this 和新实例之间的关系,请考虑以下示例:

    示例: http://jsfiddle.net/M2prR/

    var test; // will hold a reference to "this"
    
    function MyConstructor() {
        test = this; // make "test" reference "this"
    }
    
       // create a new instance
    var inst = new MyConstructor;
    
       // see if they are the same object. This will alert "true"
    alert( inst === test );
    

    【讨论】:

    • 谢谢,很清楚。 this 指的是正在创建的实例,而不是构造函数。回想起来很明显!
    • 验证:a.hasOwnProperty('x') // => TRUE(确认xa的一个属性,并且没有通过遵循原型链来检索。)
    • @Benji XVI:不客气。我添加了一个示例来进一步说明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    相关资源
    最近更新 更多