对象的 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