2013年1月25日 星期五

使用 prototype 設定 variable 需小心……

這是最近使用 prototype 設定某個 class 時發現的事……
(function(){
function T(){}
T.prototype.P = []

return (new T).P == (new T).P
})()

現在問題來了……
請問上述程式 return 的值是什麼?
回答 false 的人請回吧……答案是 true

有寫過 javascript 程式的人都知道,對任意 object :
(function(){
	var a = {};
var b = {};
return a == b
})()//return 的值為“false”
但是
(function(){
	var a = {};
var b = a;
return a == b
})()//return 的值為“true”

同理,把第一個程式碼稍微修改一下……
(function(){
function T(){}
T.prototype.P = []

var a = new T
var b = new T
return a.P == b.P
})()

則因為 a.constructor == b.constructor && a.constructor == T
prototype 是建立在 constructor 上的。
則 a.P == T.prototype.P ;同理 b.P == T.prototype.P ,兩邊都是 constructor 的 prototype 的 variable,自然值是相等的! 要避免這點,則需要改為:
(function(){
function T(){
this.P = []
}
T.prototype.P = []

var a = new T
var b = new T
return a.P == b.P
})()

沒有留言:

張貼留言