DIV CSS 佈局教程網

JavaScript 的四個關鍵屬性:this、prototype、constructor 與原型鏈
編輯:JavaScript綜合知識     

this、prototype、constructor 這三個東西,是 JavaScript 面試與 debug 的必經關卡。它們彼此扣得很緊,分開看都懂,合起來看就暈。這篇用可執行的片段把它們串成一個整體。

一、this:執行期才決定指向

this 指代當前物件。在全域作用範圍內使用時,它指向 window;在函式內使用時,它指向「執行時是誰呼叫了這個函式」——不是定義時寫在哪裡。

console.log(this === window);          // true(全域)
console.log(window.alert === this.alert);   // true

函式中的 this 在執行時決定:

function foo() { console.log(this.fruit); }
var fruit = "apple";
foo();            // apple,this 是 window

var pack = { fruit: "banana", foo: foo };
pack.foo();       // banana,this 是 pack

apply 與 call 可以強制改變 this 的指向,兩者唯一差別在參數傳遞形式:

function foo() { console.log(this.fruit); }
var fruit = "apple";
var pack = { fruit: "banana" };

foo.apply(window);   // apple
foo.apply(pack);     // banana

因為函式在 JavaScript 中也是物件,所以會出現這種有趣的情況:

function foo() {
  console.log(this === window ? "window" : "not window");
}
foo.boo = function () {
  console.log(this === foo ? "foo" : (this === window ? "window" : "?"));
};

foo();                  // window
foo.boo();              // foo
foo.boo.apply(window);  // window

二、prototype:每個函式都有一個

prototype 本質上就是一個 JavaScript 物件,而且每個函式都有一個預設的 prototype 屬性。當這個函式被用來建立自訂物件時,我們稱它為建構式。

function Person(name) {
  this.name = name;
}
Person.prototype = {
  getName: function () { return this.name; }
};

var zhang = new Person("Zhang");
console.log(zhang.getName());   // Zhang

以此類推,JavaScript 的內建型別——String、Number、Array、Object、Date——內部都是以建構式實作的:

function Array() { }
var arr1 = new Array(1, 56, 34, 12);
var arr2 = [1, 56, 34, 12];

而陣列的許多方法(concat、join、push)應該也是定義在 prototype 上的。事實上,所有內建型別都具有唯讀的 prototype 屬性——這可以理解的,否則改了它,預定義的方法就全消失了——但我們可以向其中擴充自己的方法:

Array.prototype.min = function () {
  var min = this[0];
  for (var i = 1; i < this.length; i++) {
    if (this[i] < min) { min = this[i]; }
  }
  return min;
};
console.log([1, 56, 34, 12].min());   // 1

這裡有個陷阱:擴充 Array 原型後,用 for-in 遍訪陣列時,這個方法也會被遍列出來:

var arr = [1, 56, 34, 12];
var total = 0;
for (var i in arr) {
  total += parseInt(arr[i], 10);      // NaN,因為 i 可能是 "min"
}

解法是用 hasOwnProperty 過濾:

for (var i in arr) {
  if (arr.hasOwnProperty(i)) {
    total += parseInt(arr[i], 10);
  }
}

三、constructor:指向建立自己的建構式

var arr = [1, 56, 34, 12];
console.log(arr.constructor === Array);        // true

var Foo = function () { };
console.log(Foo.constructor === Function);     // true
var obj = new Foo();
console.log(obj.constructor === Foo);          // true
console.log(obj.constructor.constructor === Function);   // true

但 constructor 遇到 prototype 時會出問題。每個函式的預設 prototype 上都有 constructor 指回這個函式:

function Person(name) { this.name = name; }
Person.prototype.getName = function () { return this.name; };

var p = new Person("Zhang");
console.log(p.constructor === Person);                          // true
console.log(Person.prototype.constructor === Person);           // true

可是如果我們覆寫(注意:不是修改,而是整個換掉)prototype:

function Person(name) { this.name = name; }
Person.prototype = {
  getName: function () { return this.name; }
};

var p = new Person("Zhang");
console.log(p.constructor === Person);        // false!
console.log(p.constructor === Object);        // true

原因:覆寫 Person.prototype 等價於這樣做:

Person.prototype = new Object({
  getName: function () { return this.name; }
});

而 constructor 永遠指向建立自身的建構式,此時就是 Object。

修正方式很簡單,補一行把 constructor 扶正:

Person.prototype = {
  getName: function () { return this.name; }
};
Person.prototype.constructor = Person;      // 關鍵的一行

var p = new Person("Zhang");
console.log(p.constructor === Person);      // true

把四個東西連起來

讀物件上的屬性時,若在自身找不到,JavaScript 會沿著 obj.__proto__ 往上找,直到 Object.prototype 為止,這條鏈就是原型鏈。new 這個運算子做的事,就是建立一個物件、把它的 __proto__ 指向建構式的 prototype、再套用建構式裡的 this 賦值。

所以:this 決定「誰的屬性被存取」,prototype 決定「找不到時去哪裡找」,constructor 只是 prototype 上一個指回建構式的便利屬性。ES6 的 class 語法底下跑的就是這一套,理解之後,那些「class 是假的」的說法你就能自己判斷了。

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