-
關(guān)于此書:
此書的首要目的是幫助讀者以Javascript這門語言的思維方式來思考弦疮,以更好的掌握這門語言。此書只關(guān)注Javascript重要的部分寒亥。
-
對象(Objects)
Javascript的基本類型包括number邮府,string,boolean(true 和 false)溉奕,null褂傀,undefined。其他的類型都是object加勤。Javascript中的object是mutable keyed collection仙辟。
<pre><code>var empty_object = {}; var stooge = { "first-name": "Jerome", "last-name": "Howard" };
</code></pre>
代碼中”first-name’的雙引號不是必須的。Javascript可以通過[]或者 . 的方式來取值鳄梅,如果值不存在則返回undefine叠国,可以通過||的方式來設(shè)置默認(rèn)值:
<pre><code>var middle = stooge["middle-name"] || "(none)"; var status = flight.status || "unknown";
</code></pre>
可以用&&來避免從undefine中取值拋異常:
<pre><code>flight.equipment // undefined flight.equipment.model // throw "TypeError" flight.equipment && flight.equipment.model // undefined
</code></pre>
object賦值是通過引用的方式而不是復(fù)制的方式
<pre><code>var x = stooge; x.nickname = 'Curly'; var nick = stooge.nickname; // nick is 'Curly' because x and stooge // are references to the same object var a = {}, b = {}, c = {}; // a, b, and c each refer to a // different empty object a = b = c = {}; // a, b, and c all refer to // the same empty object
</code></pre>
typeof以字符串的方式返回object的類型:
<pre><code>
typeof flight.number // 'number' typeof flight.status // 'string' typeof flight.arrival // 'object' typeof flight.manifest // 'undefined'
</code></pre>
hasOwnProperty返回true,如果object有該屬性卫枝。
<pre><code>
flight.hasOwnProperty('number') // true flight.hasOwnProperty('constructor') // false
</code></pre>
for in可用來遍歷object的屬性煎饼,可以用typeof來過濾函數(shù)屬性:
<pre><code>
var name; for (name in another_stooge) { if (typeof another_stooge[name] !== 'function') { document.writeln(name + ': ' + another_stooge[name]); } }
</code></pre>
delete可以用來刪除object的屬性,刪除屬性并不影響到prototype的屬性
<pre><code>
another_stooge.nickname // 'Moe' // Remove nickname from another_stooge, revealing // the nickname of the prototype. delete another_stooge.nickname; another_stooge.nickname // 'Curly'
</code></pre>
可以定義一個全局變量校赤,作為程序的命名空間吆玖,以免污染全局命名空間:
<pre><code>
var MYAPP = {}; MYAPP.stooge = { "first-name": "Joe", "last-name": "Howard" }; MYAPP.flight = { airline: "Oceanic", number: 815, departure: { IATA: "SYD", time: "2004-09-22 14:55", city: "Sydney" }, arrival: { IATA: "LAX", time: "2004-09-23 10:42", city: "Los Angeles" } };
</code></pre>