2013-12-16 42 views
0

我明確地定義剛剛創建的對象的constructor屬性如下所示:應用構造屬性沒有結果

var fooProto={foo:"prototype"}; 
function f(){ }; 
f.prototype=fooProto; 
var object= new f(); 
object.constructor.prototype.bar="bar"; 
console.log(object.foo, Object.prototype.bar); 

在我們prototype,bar控制檯,但我明確undefined,undifined。請解釋爲什麼發生?

+1

我不明白這個問題的構造。 *「但我是明確的未定義的,未定義的。」*是什麼意思? –

+0

我認爲你的意思是我'期待' – HMR

回答

1

要添加扎到Object.prototype中:

console.log(fooProto.constructor===Object);//true 
console.log(object.constructor.prototype===fooProto);//true 

設置的f()原型後,您應該修復構造:

f.prototype=...; 
f.prototype.constructor=f; 

如果你期待不確定的,那麼我不確定我剛剛回答爲什麼第二個不打印未定義。

爲什麼第一個不是undefined在構造函數的介紹中回答了here。簡短的回答;當你在一個對象上請求成員並且該對象沒有該成員/屬性時,JS將在創建該對象的構造函數的原型上查找它。

例如:

var test = {}; 
console.log(test.hasOwnProperty);//=hasOwnProperty(), not undefined 

測試沒有hasOwnProperty所以在哪裏它從何而來?

console.log(test.constructor);//=Object() 
console.log(test.constructor.prototype.hasOwnProperty 
    ===test.hasOwnProperty);//=true 

因此,測試從Object.prototype中得到hasOwnProperty和對象是測試

相關問題