DIV CSS 佈局教程網

用函式建構物件:JavaScript 的建構函式與屬性存取
編輯:JavaScript綜合知識     

在 ES2015 的 class 語法出現之前,JavaScript 用函式來建立物件,這是最經典的做法。理解它,才能真正看懂原型繼承與 this 的運作。

範例

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>利用函式實現物件</title>
<script type="text/javascript">
function Person(name, age) {
  // 定義屬性,同時完成初始化
  this.name = name;
  this.age = age;

  // 定義方法
  this.ShowInfo = function () {
    alert("name:" + this.name + "--age:" + this.age);
  };
}

var ZhangShan = new Person("張三", 30);

// 注意:第一個屬性用中括號取值,可以動態傳入屬性名稱
alert("Name:" + ZhangShan["name"] + ",Age:" + ZhangShan.age);

ZhangShan.ShowInfo();
</script>
</head>
<body></body>
</html>

逐段拆解

Person 表面上是個普通函式,但當它以 new 呼叫時就變成建構函式。JavaScript 在此時會做三件事:建立一個新物件、把它的原型指向 Person.prototype、然後以該物件作為 this 執行函式本文。

函式內的 this.name = name 因此是在「往新物件上掛屬性」,而 this.ShowInfo = function(){} 則是掛上一個方法。

兩種屬性取值語法

ZhangShan.name;      // 點記法
ZhangShan["name"];   // 中括號記法

兩者結果相同,但中括號的好處是鍵名可以是變數或運算式:

var key = "name";
ZhangShan[key];       // "張三"

// 也可搭配迴圈動態走訪
for (var k in ZhangShan) {
  console.log(k + ": " + ZhangShan[k]);
}

new 的關鍵:this 綁定

如果忘記寫 new,直接呼叫 Person("李四", 25),在非嚴格模式下 this 會指向全域物件,屬性就被掛到 window 上,而函式回傳 undefined。這是最常見的 bug 之一。防呆方式是在函式開頭加上:

function Person(name, age) {
  if (!(this instanceof Person)) {
    return new Person(name, age);
  }
  this.name = name;
  this.age = age;
}

方法應該放在原型上

範例把 ShowInfo 定義在 this 上,這意味著每建立一個物件就會複製一份函式,開銷不必要的。更好的做法:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.showInfo = function () {
  alert("name:" + this.name + "--age:" + this.age);
};

這樣所有 Person 實例共用同一個函式,透過原型鏈找到它。今天的寫法則是:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  showInfo() {
    alert(`name:${this.name}--age:${this.age}`);
  }
}

class 語法本質上只是原型繼承的語法糖,方法自動掛在 prototype 上,正是上面改良後的行為。

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