-
关于此书:
此书的首要目的是帮助读者以Javascript这门语言的思维方式来思考,以更好的掌握这门语言。此书只关注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,可以通过||的方式来设置默认值:
<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赋值是通过引用的方式而不是复制的方式
<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来过滤函数属性:
<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>
网友评论