DIV CSS 佈局教程網

JavaScript 物件導向學習筆記(二):Object 原型方法、原型鏈與 instanceof
編輯:JavaScript基礎知識     

Object 原型上值得記牢的四個方法

1、constructor
語法:建構函式.prototype.constructor
作用:指回建構函式本身。

function Person(){}
console.log(Person === Person.prototype.constructor); // true

2、hasOwnProperty
語法:物件.hasOwnProperty(屬性名)
作用:分辨這個屬性是物件自有的,還是沿原型鏈繼承來的。

function Person () {}
Person.prototype.name = "landmine";
var p = new Person();
p.age = 18;
console.log(p.hasOwnProperty("name")); // false,繼承而來
console.log(p.hasOwnProperty("age"));  // true,自己就有

3、isPrototypeOf
語法:物件1.isPrototypeOf(物件2)
作用:判斷物件1 是否為物件2 的原型物件。

function Person () {}
var p = new Person();
console.log(Person.prototype.isPrototypeOf(p)); // true

4、propertyIsEnumerable
語法:物件.propertyIsEnumerable(屬性名)
作用:判斷該「自有屬性」是否可被 for-in 枚舉。若屬性不可枚舉、根本不存在,或並非自有屬性,一律回傳 false。

function Person () { this.age = 18 }
var p = new Person();
p.name = "landmine";
console.log(p.propertyIsEnumerable("name"));   // true
console.log(p.propertyIsEnumerable("age"));    // false,設在建構函式 this 上仍非原型鏈上的可枚舉自有屬性
console.log(p.propertyIsEnumerable("gender")); // false,不存在

原型鏈的七條規則

1、物件都有原型物件,且預設繼承自它。

2、函式在被定義之後,預設就帶有一個原型屬性,而這個原型屬性本身也是物件。

3、函式的原型屬性預設繼承自 Object.prototype。

4、原型物件上的 constructor 指回對應的建構函式。

5、所有函式都是 Function 的實例。

6、函式也是物件,因此函式的屬性預設繼承自 Function.prototype。

7、Function 自己也是函式,即 Function.__proto__ === Function.prototype。

兩個最容易混淆的概念:

· prototype 是函式的原型屬性,也就是這個函式所建之物件的原型物件。

· __proto__ 是物件自己的原型物件,也就是建立它的建構函式的原型屬性。

整體的原型鏈圖像如下:

instanceof 運算子

語法:物件 instanceof 建構函式
作用:判斷該建構函式是否出現在物件原型鏈上的某一環。

function Foo() {}
function Fn() {}
var f1 = new Fn();
console.log(f1 instanceof Fn);     // true
console.log(f1 instanceof Object); // true
Fn.prototype = new Foo();          // 換掉函式的原型鏈
var f2 = new Fn();
console.log(f1 instanceof Foo);    // false
console.log(f2 instanceof Foo);    // true

關鍵在於:把 Fn.prototype 改指向 Foo 之後,只有「之後才建立的」f2 會走上新鏈條;f1 早在建立時就已經綁定舊鏈,因此 Foo 並不在它的原型鏈上。

若想補救,可以直接改物件的 __proto__,在上面的基礎上追加:

f1.__proto__ = new Foo();
console.log(f1 instanceof Foo); // true

用 new Function 動態建立函式

語法:var 函式名 = new Function(arg1, arg2, ..., argN, body);
作用:動態組出函式,參數清單中的最後一項是函式主體,其餘都是形參。

var fnMax = new Function('a', 'b', 'return a > b ? a : b;');
var res = fnMax(1, 2);
console.log(res); // 2

這種寫法等同於 eval,會跳過編譯期的優化,效能與可讀性都不理想,實務上多半只在需要動態產生程式碼的場景才動用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved