2015-06-14 17 views
1

我下面的代碼是這樣的:如果他沒有名字,是什麼使構造函數的object.prototype?

var triangle = {a:1, b:2, c:3}; 

function constructorFunction() { 
    this.color = "red"; 
} 

constructorFunction.prototype = triangle; 

我知道原型關鍵字在這句法擴展類:Object.prototype.method = function() {}但什麼是這個例子嗎?在constructorFunction.prototype之後沒有屬性或方法名稱,這裏會發生什麼?

+0

不,這有點不同。 –

+0

'prototype'不是關鍵字。 '.prototype'是'constructorFunction'的一個簡單屬性。 – Bergi

+0

'.prototype'只能與'new'運算符一起使用。 要在不使用'.prototype'的情況下設置_real_ [[[prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#Inheritance_with_the_prototype_chain)]](內部鏈接,\ __ proto__)使用'Object.create(real_prototype)'或'Object.setPrototypeOf(existing_object,new_real_prototype)' – befzz

回答

2

constructorFunction.prototype後沒有propertie或方法名

這不是真的。構造函數的prototype是使用triangle對象設置的。該prototype有3個屬性。

prototype是一個對象。考慮以下示例:使用對象文本

var obj = { 'baz': 'bar' }; 
obj = { 
    'foo': 'bash' 
} 
// obj => { 'foo': 'bash' } 

在上述代碼段中的obj變量的值是復位

var obj = { 'baz': 'bar' }; 
obj.foo = 'bash'; 

// obj => { 'baz': 'bar', 'foo': 'bash' } 

在上述例子中的原始目的是通過使用點符號擴展

我試着console.log(constructorFunction.a);但它返回undefined。

這是因爲您還沒有創建實例。 a是構造函數的prototype對象的屬性。

console.log(constructorFunction.prototype.a); 

如果您創建一個實例對象,那麼a是該實例的一個屬性。

var ins = new constructorFunction(); 
console.log(ins.a); 
+0

但我無法接受這些屬性,我試着console.log(constructorFunction.a);但它返回undefined。 –

+0

我在想,constructorFunction是用三角形對象擴展的,我可以使用它,不是嗎? –

+0

@AlanasMacijauskas你可以像下面這樣訪問它:'constructorFunction.prototype.a'。請記住,您沒有將'triangle'分配給'constructorFunction',而是分配給'constructorFunction.prototype'。 – slebetman

相關問題