JavaScript 繼承 聖盃模式
阿新 • • 發佈:2018-12-19
- 發展史
1.傳統形式 --> 原型鏈
過多的繼承了沒用的屬性
2.借用建構函式
不能繼承借用建構函式的原型
每次建構函式都要走一個函式
3.共享原型
不能隨便改動自己的原型
4.聖盃模式
// 1. 繼承了所有資訊 Grand.prototype.lastName = 'zhang'; function Grand() {} var grand = new Grand(); Father.prototype = grand; function Father() { this.name = 'san'; } var father = new Father(); Son.prototype = father; function Son = new Son(); // 2. 借用建構函式 每次都要用new function Person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } function Student(name, age, sex, grade) { Person.call(this, name, age, sex); this.grade = grade; } var student = new Student('xiaoming', 19, 'male', 2018); // 3. 共用原型 Father.prototypoe.lastName = 'zhang'; function Father() {} function Son() {} function inherit(Target, Origin) { Target.prototype = Origin.prototype; } inherit(Son, Father); // Son.prototype = Father.prototype var son = new Son(); console.log(son.lastName); // 'zhang' Son.prototype.sex = 'male'; console.log(son.sex); // 'male' var father = new Father(); console.log(father.sex); // 'male' // 4. 聖盃模式 function inherit(Target, Origin) { function F() {}; F.prototype = Origin.prototype; Target.prototype = new F(); Target.prototype.constuctor = Target; Target.prototype.uber = Origin.prototype; // 超級父級 } // 4.1 聖盃模式 var inherit = (function(){ var F = function(){}; // 私有化變數 外部無法訪問 return function (Target, Origin) { F.prototype = Origin.prototype; Target.prototype = new F(); Target.prototype.constuctor = Target; Target.prototype.uber = Origin.prototype; } }())