DIV CSS 佈局教程網

淺談 JavaScript 原型鏈與繼承
編輯:關於JavaScript     

原型鏈與繼承是 JS 的重點,本文透過幾個實例詳細講解。

首先定義一個物件 obj,它的原型為 obj.__proto__,我們可以用 ES5 的 getPrototypeOf 方法查詢。透過判斷 obj 的原型是否與 Object.prototype 相等,就能證明原型是否存在,結果回傳 true,代表存在。接著定義一個函式 foo(),任何函式都有它的 prototype 物件(即函式的原型),我們可以在原型上加任意屬性,之後透過 new 建立的實例就能共享這些屬性。

 function foo(){}
 foo.prototype.z = 3;
 var obj = new foo();
 obj.x = 1;
 obj.y = 2;
 obj.x //1
 obj.y //2
 obj.z //3
 typeof obj.toString; //function
 obj.valueOf(); // foo {x: 1, y: 2, z: 3}
 obj.hasOwnProperty('z'); //false

在這裡,obj 的原型(__proto__)指向 foo 函式的 prototype 屬性,foo.prototype 的原型指向 Object.prototype,原型鏈的末端則為 null。透過 hasOwnProperty 查看 z 屬性是否直接在 obj 上,顯示 false,代表 obj 本身沒有 z,但沿著原型鏈查找,發現 foo.prototype 上有,所以 obj.z = 3。obj.valueOf() 與 toString 也都來自 Object.prototype,因此任何物件都有這兩個屬性。唯一的特例是:

 var obj2 = Object.create(null);
 obj2.valueOf(); //undefined

Object.create() 會建立一個空物件,且其原型指向傳入的參數。下面用一個綜合實例展示如何讓一個 class 繼承另一個 class:

 // 宣告一個建構函式 Person
 function Person(name, age) {
 this.name = name;
 this.age = age;
 }
 Person.prototype.hi = function () {
 console.log('Hi,my name is ' + this.name + ',my age is ' + this.age);
 };
 Person.prototype.LEGS_NUM = 2;
 Person.prototype.ARMS_NUM = 2;
 Person.prototype.walk = function () {
 console.log(this.name + ' is walking !');
 };

 function Student(name, age, classNum) {
 Person.call(this, name, age);
 this.classNum = classNum;
 }
 // 建立一個空物件,其原型指向 Person.prototype
 Student.prototype = Object.create(Person.prototype);
 // 指定建立物件的函式
 Student.prototype.constructor = Student;
 Student.prototype.hi = function () {
 console.log('Hi,my name is ' + this.name + ',my age is ' + this.age + ' and my class is ' + this.classNum);
 };
 Student.prototype.learns = function (sub) {
 console.log(this.name + ' is learning ' + sub);
 };

 var Bosn = new Student('bosn', 27, 'Class 3');
 Bosn.hi(); //Hi,my name is bosn,my age is 27 and my class is Class 3
 Bosn.LEGS_NUM; //2
 Bosn.walk(); //bosn is walking !
 Bosn.learns('Math'); //bosn is learning Math

建構函式 Person 與 Student 的 this 都指向實例化的物件(Bosn),而該物件的原型指向建構器的 prototype。用 Object.create() 建立一個原型指向 Person.prototype 的空物件,好處是不影響 Person.prototype 的前提下,能自由建立 Student.prototype 的屬性,同時繼承 Person.prototype 上原有的屬性。若直接寫 Student.prototype = Person.prototype,兩者會指向同一物件,添加屬性時會互相影響。

至於建構函式 Student 裡的 call 方法,其 this 指向新建立的 Student 實例,藉此完成繼承。而 Student.prototype.constructor = Student 這句話是指定 Student 為建立該 prototype 物件的函式,若不寫,該函式仍會是 Person。

繼承一共有三種實作方式:

 function Person(name, age){
 this.name = name;
 this.age = age;
 }
 function Student(){}
 Student.prototype = Person.prototype; // 1
 Student.prototype = Object.create(Person.prototype); // 2
 Student.prototype = new Person(); // 3

第一種會讓子類與基類指向同一物件,不建議;第二種恰到好處地避開這個問題,讓實例先查詢子類,若無屬性再查詢基類,是較好的選擇;第三種雖也實現繼承,但呼叫了 Person 建構函式,此例中它需要 name 與 age 兩個參數卻沒有傳入,並未真正實例化。以上就是本文的完整內容,希望對大家有所幫助。

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