在构造函数中声明*的属性在实例中可见.为什么?

Ben*_*XVI 1 javascript oop inheritance prototype this

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

可以解析构造函数的"prototype"属性的属性,就好像它们是对象实例的属性一样.但是,实例无法访问构造函数对象的实际属性:

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

a = new MyConstructor()
a.x == 3    // FALSE
a.y == 7    // TRUE
Run Code Online (Sandbox Code Playgroud)

然而,如果属性(" x构造器")的函数体与声明this的关键字,这些特性当然的情况下解决的:

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

a = new MyConstructor()
a.x == 3    // TRUE
Run Code Online (Sandbox Code Playgroud)

为什么?有什么不同?

use*_*716 6

当你这样做:

MyConstructor.x = 3;
Run Code Online (Sandbox Code Playgroud)

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

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

当构造运行,this 正在被返回的对象.所以它只是一个方便,所以你不必这样做:

a = new MyConstructor();
a.x = 3;
a.x == 3    // TRUE!
Run Code Online (Sandbox Code Playgroud)

因为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 );
Run Code Online (Sandbox Code Playgroud)