Js 構造函數的繼承


Js 構造函數的繼承

在上一篇  文章 中講述了 Js 對象、構造函數以及原型模式,這篇文章來討論下 JavaScript 的繼承。
繼承是 OO 語言中的一個最為人津津樂道的概念。許多 OO 語言都支持兩種繼承方式:接口繼承和實現繼承。接口繼承只繼承方法簽名,而實現繼承則繼承實際的方法。如前所述,由於函數沒有簽名,在 ECMAScript 中無法實現接口繼承。ECMAScript 只支持實現繼承,而且其實現繼承主要是依靠原型鏈來實現的。

一、使用 call 或 apply

假如有一個 "人" 對象,還有一個 "學生" 對象。
function Person(name, age) {
    this.name = name;
    this.age = age;
}

function Student(subject) {
    this.subject = "語文";
}
我們怎樣才能使 "人" 對象繼承 "學生" 對象的屬性或方法呢。第一種方法,也是最簡單的方法,使用 call 或 apply 來改變 this 指向使其調用對象的屬性或方法。
function Person(name, age) {
    this.name = name;
    this.age = age;
    Student.call(this, name, age);
}
var person1 = new Person("張三", "18");
console.log(person1.subject) // 語文

二、prototype

第二種方法是使用 prototype 屬性。也就是說使用 "人" 的 prototype(原型) 對象指向 Student 的實例對象,那么所有 "人" 的實例,就能繼承 "學生"了。
1、先將 Person 的 prototype 對象指向一個 Student 對象的實例。
Person.prototype = new Student();
// 等於覆蓋或者刪除了原先的 prototype 對象的值,然后給予一個新值
2、把 Person 的 prototype 對象的 constructor 屬性在指回 Person。
Person.prototype.constructor = Person;
// 任何一個 prototype 對象都具有一個 constructor 屬性,指向它的構造函數
// 如果不加這下一行代碼,Person.prototype.constructor 會指向 Student
3、每一個實例也會有一個 constructor 屬性,默認調用 prototype 對象的 constructor 屬性。
var person1 = new Student("張三","18");
alert(person1.constructor == Person.prototype.constructor); // true
// 因此在運行 Person.prototype = new Student() ,person1.constructor 也指向 constructor
// 所以因該手動修改 constructor 的指向
// 總代碼
function Person(name, age) {
    this.name = name;
    this.age = age;
}

function Student(subject) {
    this.subject = "語文";
}

Person.prototype = new Student();
Person.prototype.constructor = Person;

var person1 = new Student("張三","18");
console.log(person1.subject); // 語文

三、繼承 prototype(原型)

直接繼承原型,我們先修改下 Student 對象的代碼,添加原型。
function Student(){};
Student.prototype.project = "語文";
然后將 Person 的 prototype 對象指向 Student 的 prototype,這樣就完成了繼承。
Person.prototype = Student.prototype;
Person.prototype.constructor = Person;

var person1 = new Student("張三","18");
console.log(person1.subject); // 語文
這樣做雖然效率高,但是下級獲取到的權限過重,並且還會修改 constructor 指向。
Person.prototype.constructor = Person;
// 這一行代碼直接把 Student.prototype.constructor 的指向給改了(Person)

四、找中間介

使用空對象,代碼如下:
var middle = function(){};
middle.prototype = Student.prototype;
Person.prototype = new middle();
Person.prototype.constructor = Person;

console.log(Student.prototype.constructor); // Student
因為 middle 是空對象,所以修改 Person 的 prototype 對象,就不會影響 Student 的 prototype 對象。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM