JavaScript 裡的物件,本質上是一組屬性(方法)的集合。存取方式有兩種:物件.屬性 與 物件["屬性"]。當屬性名不符合識別符規範(例如含有空白或連字號)時,就必須改用中括號。
var a = new class1();
a.name;
a['name']; // 等價寫法
arr['push']('abc'); // 中括號適合不確定要引用哪個方法的場合
function class1() {
this.name = "xjl"; // 加入屬性
this.say = function () { alert("大家好!"); }; // 加入方法
}
var a = new class1();
new 不只對內建類別有效,對自訂的「類別」也同樣適用。
var obj = new Object();
obj.name = "徐建龍";
obj.sex = '男';
obj['my name'] = "xujianlong"; // 中括號可用非識別符字串當屬性名
obj.alert = function (a) { alert(a + "你好!"); };
obj.name = "張三"; // 修改
obj.name = undefined; // 「刪除」——實務上建議用 delete obj.name
嚴格來說把值設為 undefined 只是讓屬性存在但值為 undefined,要真正移除應該用 delete。
var ob = {
name: "123",
say: function () { alert("123"); } // 最後一項不加大括號前的逗號
};
var ob1 = { "name": '123', "say": function () { alert("abcd"); } };
所有 function 對應的類別是 Function;prototype 基本上代表「這個類別的成員集合」。透過 new 建立實例時,prototype 上的成員都會成為實例可用的成員。
function class2() {}
class2.prototype.me = function () { alert("123"); };
class2.prototype.name = "123";
var ob2 = new class2();
也可以整體替換:
class1.prototype = {
// 多個屬性或方法用逗號隔開
};
而 class1.name = "abc" 這種掛在函式本身上的寫法,屬於靜態屬性與靜態方法,實例取不到。
函式有一個隱含參數 arguments,具備陣列特性(可用下標存取)但不是真的陣列。其中的 callee 指向函式本身,適合做遞迴:
var sum = function (n) {
if (1 == n) return 1;
else return n + arguments.callee(n - 1);
};
var namespace1 = new Object();
namespace1.class1 = function () { alert("123"); };
var obj1 = new namespace1.class1();
繼承可以透過複製 prototype 達成,但直接指派 class2.prototype = class4.prototype 有嚴重缺陷——改動 class2 的 prototype 會連帶影響 class4。比較好的做法是逐個屬性複製:
for (var p in class1.prototype) {
class2.prototype[p] = class1.prototype[p];
}
class2.prototype.ma = function () { alert(123); };
或者用 Prototype 框架那種 extend 模式:
Object.extend = function (destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
};
class1.prototype = (new class2()).extend({ /* class1 要新增的成員 */ });
用 instanceof 可以判斷物件是否為某類別的實例(含繼承而來的子類別)。
只宣告而未實作的成員,等同虛函式;含虛函式的類別稱為抽象類別,不可直接實例化,需由派生類實作:
function c1() {}
c2.prototype = { fun: function () { this.fn(); } }; // fn 未定義
function c2() {}
c1.prototype = (new c2()).extend({ fn: function () { var x = 1; } });
function setStyle(_style) {
var element = getElement();
for (var p in _style) {
element.style[p] = _style[p];
}
}
function s(a, b) {
try {
if (b == 0) throw new Error("除數不能為零!");
else alert(a / b);
} catch (e) {
document.write(e.message); // 透過 message 取得錯誤描述
}
}
s(1, 0);
catch (e) 中的 e 是必需的,它是一個 Error 物件;用 new Error(message) 建立,描述會放在 message 屬性上。