對象的 prototype
屬性的方法、屬性爲對象所屬的那一「類」所共有。對象原型鏈經過 __proto__
屬性向上尋找。
爲 __proto__
指定 null
以外的原始類型(Number
, String
, Boolean
, undefined
, Symbol
)值是無效的。
經過構造函數或者 {}
方式建立的對象的 prototype
屬性默認爲 undefined
函數
{}
的繼承var a = { x: 10, calculate: function (z) { return this.x + this.y + z; } }; var b = { y: 20, __proto__: a }; var c = { y: 30, __proto__: a }; // call the inherited method b.calculate(30); // 60 c.calculate(40); // 80
若是沒有明確指定,那麼 __proto__
默認爲 Object.prototype
,而Object.prototype
自身也有 __proto__
,值爲 null
,是原型鏈的終點。this
If a prototype is not specified for an object explicitly, then the default value for
__proto__
is taken —Object.prototype
. ObjectObject.prototype
itself also has a__proto__
, which is the final link of a chain and is set tonull
.spa
// a constructor function function Foo(y) { // which may create objects // by specified pattern: they have after // creation own "y" property this.y = y; } // also "Foo.prototype" stores reference // to the prototype of newly created objects, // so we may use it to define shared/inherited // properties or methods, so the same as in // previous example we have: // inherited property "x" Foo.prototype.x = 10; // and inherited method "calculate" Foo.prototype.calculate = function (z) { return this.x + this.y + z; }; // now create our "b" and "c" // objects using "pattern" Foo var b = new Foo(20); var c = new Foo(30); // call the inherited method b.calculate(30); // 60 c.calculate(40); // 80 // let's show that we reference // properties we expect console.log( b.__proto__ === Foo.prototype, // true c.__proto__ === Foo.prototype, // true // also "Foo.prototype" automatically creates // a special property "constructor", which is a // reference to the constructor function itself; // instances "b" and "c" may found it via // delegation and use to check their constructor b.constructor === Foo, // true c.constructor === Foo, // true Foo.prototype.constructor === Foo, // true b.calculate === b.__proto__.calculate, // true b.__proto__.calculate === Foo.prototype.calculate // true );
若是沒有明確指定,經過構造函數建立的對象的 __proto__
屬性值爲構造函數的 prototype
屬性。prototype