DIV CSS 佈局教程網

JavaScript 三大關鍵屬性詳解:this、prototype 與 constructor
編輯:JavaScript基礎知識     

要真正讀懂 JavaScript 的物件模型,this、prototype 與 constructor 這三個屬性幾乎是必經關卡。它們彼此扣連,理解一個往往能帶出另外兩個的意義。

this:執行期才決定的「當前物件」

this 代表當前物件。在全域作用域中使用時,它指向頁面物件 window;在函式內部使用時,它指向「執行期呼叫這個函式的物件」,也就是說 this 的價值在函式被呼叫的那一刻才確定,而不是在定義時。

console.log(this === window);          // true
console.log(window.alert === this.alert);   // true
console.log(this.parseInt("10", 10));  // 10

函式中的 this 同樣是執行期決定:

function foo() {
  console.log(this.fruit);
}

var fruit = "apple";
foo();                        // apple,this 指向 window

var pack = {
  fruit: "orange",
  foo: foo
};
pack.foo();                   // orange,this 指向 pack

若想在呼叫時強制指定 this,可以借用 apply 與 call 這兩個全域方法:

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

apply 與 call 的作用完全相同,唯一的差別是參數形式不同:call 逐一列出參數,apply 則接受一個陣列。

因為在 JavaScript 中函式本身也是物件,所以還能看到這類有趣的寫法:

function foo() {
  if (this === window) {
    console.log("window");
  }
}

foo.boo = function () {
  if (this === foo) {
    console.log("foo");
  }
  if (this === window) {
    console.log("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 San");
console.log(zhang.getName());

以此類推,JavaScript 的內建型別——字串、數字、陣列、物件、日期——內部大概都是以建構函式實作的:

function Array() {}

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

而我們每天在用的陣列方法(concat、join、push 等),自然也定義在 prototype 上。事實上,JavaScript 所有固有型別都具有唯讀的 prototype 屬性——這很合理,否則一改,預定義好的方法就全消失了——但我們仍然可以往裡頭擴充自己的方法:

Array.prototype.min = function () {
  var min = [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);
}
console.log(total);   // 結果多出了函式轉數字造成的 NaN

解法很簡單,用 hasOwnProperty 過濾掉繼承而來、非自有的屬性:

var arr = [1, 56, 34, 12];
var total = 0;
for (var i in arr) {
  if (arr.hasOwnProperty(i)) {
    total += parseInt(arr[i], 10);
  }
}
console.log(total);

constructor:回指產生自己的建構函式

constructor 永遠指向建立當前物件的建構函式:

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

function Foo() {}
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 屬性,而這個 prototype 的 constructor 預設指回該函式。下面的例子是「往 prototype 上逐步加方法」,因此關係依然完整:

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

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

但如果我們整個覆寫 prototype(注意:這裡是替換,不是修改),constructor 的行為就變得莫名其妙:

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

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

原因在於,覆寫 Person.prototype 等同於執行下面的操作:

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

而 constructor 永遠指向建立自己的建構函式,於是此時 Person.prototype.constructor === Object:

console.log(p.constructor === Object);                      // true
console.log(Person.prototype.constructor === Object);        // true
console.log(p.constructor.prototype.constructor === Object); // true

要修正也很容易,覆寫 prototype 之後,記得把 constructor 補回去:

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

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

把這三個屬性串起來看:this 決定「現在是誰」,prototype 決定「物件共享哪些能力」,constructor 則是「我從哪裡來」的線索。理解它們的互動關係,型別判斷與繼承實作就不再靠死記。

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