开发者

Properties declared *in* the Constructor are visible in instances. Why?

开发者 https://www.devze.com 2023-02-04 08:36 出处:网络
In Javascript’s system of prototypal inheritance, an object’s internal prototype reference is set to its constructor’s “prototype” pr开发者_Go百科operty, which is itself an object.

In Javascript’s system of prototypal inheritance, an object’s internal prototype reference is set to its constructor’s “prototype” pr开发者_Go百科operty, which is itself an object.

Properties of the constructor’s “prototype” property may be resolved as if they were properties of object instances. However, the actual properties of the constructor object are not accessible to the instance:

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

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

However, if the property (“x”) of the constructor is declared in the function body with the this keyword, these properties are of course resolved by instances:

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

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

Why? What is the difference?


When you do this:

MyConstructor.x = 3;

...you've only added a property to the Function object instance referenced by MyConstructor. A Function object has many properties that do not become part of the instance (nor would you want them to).

As such, the mechanism for creating instance properties via the constructor is to use the this.x method.

When the constructor runs, this is the object that is being returned. So it is just a convenience so you don't have to do:

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

Because this in the constructor is the same as the resulting object, there's no need to do it explicitly upon each new instance creation.

The prototype object is simply an object that is referenced by all instances of MyConstructor so if there isn't a property on the instance, it then goes to the prototype to find one.


To illustrate the relationship between this and the new instance, consider this example:

Example: 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 );
0

精彩评论

暂无评论...
验证码 换一张
取 消