基本上,通過「。」訪問對象的屬性沒有區別。語法或通過鍵。
var obj = new function(){this.x = "value";}
alert(obj.x === obj['x']); //it will output true
有時您不能使用「。」 ,因爲你要訪問的屬性的名稱是不是有效的變量名稱(如你與你的數字鍵指出):
var obj = new function(){this['my-value'] = "my value";}
alert(obj['my-value']); // it will output "my value"
alert(obj.my-value); // it will trigger an exception , because the javascript
//interpretor interprets "obj.my-value" as the
//property "my" of obj minus the variable "value"
最大的區別就是瀏覽器處理你的語法的方式。正如你可以看到here,我的一個朋友做了一些測試,看起來Chrome和IE使用點語法工作得更快,而Firefox和Safari更關注關鍵語法。
總之,幾乎每次都可以使用其中任何一個,儘管存在「。」的情況。有點「毫無準備」。
關於原型語法,當您定義一個對象時,您可以將成員附加到每個實例,但您也可以將成員附加到該對象的原型,這意味着無論何時創建了已定義類型的新對象,它會自動從它的原型繼承該成員。我認爲這是更好地理解一個例子:
function Point(x,y){this.x = x;this.y = y;}
Point.prototype.toString = function(){
return "I am a point with my x coord at "+this.x+" and my y coord at "+this.y;
}
function Point2(x,y){
this.x = x;
this.y = y;
this.toString = function(){
return "I'm a point too.I'm at x:"+this.x+", y:"+this.y;
};
}
當你創建一個new Point2
,這是toString
方法的實例方法和JavaScript解釋器這種方法分配內存。
當你創建一個'新點'時,它的toString
方法將被鏈接在它的原型屬性上。這意味着沒有內存分配給該方法。
var p = [], p2 = [];
for(var i = 0; i < 100000000; i++)
{
p.push(new Point(0,0));
p2.push(new Point2(0,0));
}
如果你測試,你會看到這兩個對象都致力於完美,但你的Point2
對象將採取更多的內存耗盡你的系統。這是爲什麼?
問題是,當你調用new Point()
的toString()
方法時,該對象意識到它沒有名爲「toString」的成員,並且它開始搜索它的原型鏈並返回找到的'toString'成員在對象的聲明中。
在上面的例子中,所有的p
的項目都會將他們的toString
方法指向原型中提到的方法,而p2
的所有項目都將指向它們的方法的每個副本。
此外,如果你以後想修改toString
方法,否則很容易修改它所有的Point
實例:
Point.prototype.toString = function(){return "I'm a smarter point";};
之後,的new Point
每個實例將返回「我是一個聰明點」當你把它叫做toString
的方法。
如果您嘗試修改Point2
實例,則會更困難。你會發現,Point2.toString = function(){return "I'm a dumber point";}
不會按預期工作,你必須手動更改方法爲每個實例:
for(var i in p2)
p2[i].toString = function(){return "I'm a dumber point";};
我會讓你決定哪種方法比較好:P
`FOO。 [...]`是一個語法錯誤 - 你可能意指`foo [ – Christoph 2011-01-19 12:09:31
其實``foo ['...']`。 `foo [「...」]`也是。 – Thai 2011-01-19 12:29:03