一、原型繼承瀏覽器
原型繼承的特色:即繼承了父類的模版,又繼承了父類的原型對象app
// 父類 function Person(name, age) { this.name = name; this.age = age; } // 父類的原型對象方法 /*Person.prototype.say = function() { console.log('hello'); }*/ Person.prototype = { constructor: Person, say: function (){ console.log(this.name) } } // 子類 function Boy(sex) { this.sex = sex; } Boy.prototype = new Person('zn',18); var b = new Boy(); console.log(b.name); console.log(b.age); b.say();
二、類繼承(只繼承模版, 不繼承原型對象) (借用構造函數的方式繼承)函數
// 父類 function Person(name, age) { this.name = name; this.age = age; } // 父類的原型對象屬性 Person.prototype.id = 1; // 子類 function Boy(name, age, sex) { // call apply Person.call(this, name, age); this.sex = sex; } var b = new Boy('張三', 20, '男'); console.log(b.name); console.log(b.age); console.log(b.sex); console.log(b.id);
三、混合繼承(借用構造函數繼承 + 原型繼承)this
// 父類 function Person(name, age) { this.name = name; this.age = age; } Person.prototype.id = 1; Person.prototype = { constructor: Person; sayName: function () { console.log(this.name); } } // 子類 function Boy(name, age, sex) { // 借用構造函數繼承 Person.call(this, name, age); this.sex = sex; } // 原型繼承 //繼承父類的原型對象 Boy.prototype = new Person(); var b = new Boy('zn', 18, '男'); console.log(b.name); console.log(b.sex); console.log(b.age); b.sayName();
四、ES5 提供的create方法 在實際開發過程當中爲了兼容低版本瀏覽器作出繼承方法以下封裝spa
var create = function(obj) { //(火狐 谷歌等) if (Object.create) { return Object.create(obj); } else { //(ie 低版本) function F() {} F.prototype = obj; return new F(); } }