js--constructor prototype

var someObj = function() { } var p = new someObj(); alert(someObj.prototype); // This works alert(p.prototype); // UNDEFINED, but why? someObj.prototype.model= "Nissan"; alert(p.model); // This works! I understand the dynamic nature of prototypes, but doesn't that mean that p.prototype === someObj.prototype?
一道来自stackoverflow的问题:http://stackoverflow.com/questions/10329821/javascript-prototype-through-object-create?answertab=active#tab-top
 

That's because prototype is a property of the constructor function, not a property of itself. However, theprototype object has a reference to the constructor, so you can access an object's prototype via itsconstructor property:

function Foo() {} Foo.prototype.foo = "bar"; var c = new Foo; console.log( c.constructor === Foo ); // true console.log( c.constructor.prototype ); // { foo: 'bar' }

However, this will not work if you overwrite the initial prototype property of the constructor function:

function Foo() {} // I overwrite the prototype property, so I lose the initial reference // to the constructor. Foo.prototype = { foo: "bar" }; var c = new Foo; console.log( c.constructor === Foo ); // false console.log( c.constructor === Object ); // true console.log( c.constructor.prototype ); // {}

That's why you're better off using the new Object.getPrototypeOf method introduced in ES5.

function Foo() {} Foo.prototype = { foo: "bar" }; var c = new Foo; console.log( c.constructor === Foo ); // false console.log( c.constructor === Object ); // true console.log( c.constructor.prototype ); // {} console.log( Object.getPrototypeOf(c) ); // { foo: 'bar' }

Another solution would have been to make sure you restore the constructor reference on the prototype:

function Foo() {} // Overwriting the initial prototype  Foo.prototype = { constructor: Foo, // restore the constructor reference foo: "bar" };
 
prototype是作为constructor的一个属性,上面提到如果把prototype覆盖,那么就找不到原先的constructor. 另外,对于这个问题,我们在定义函数的时候,函数定义的时候函数本身就会默认有一个prototype的属性,而我们如果用new 运算符来生成一个对象的时候就没有prototype属性,可以这么理解.

你可能感兴趣的:(js,prototype,Constructor)