本文共 1714 字,大约阅读时间需要 5 分钟。
- 原型链
function SuperType(){ this.property = true;}SuperType.prototype.getSuperValue = function(){ return this.property;}function SubType(){ this.subproperty = false;}// 通过将原型指向另一个类型的事例来继承SubType.prototype = new SuperType();复制代码
- 借用构造函数
function SuperType(){ this.colors = ['red','blue','green'];}function SubType(){ // 继承了SuperType SuperType.call(this)}复制代码
- 组合继承(伪经典继承)
function SuperType(name){ this.name = name; this.colors = ['red','blue','green']}SuperType.prototype.sayName = function(){ alert(this.name)}function SubType(name,age){ // 继承属性 SuperType.call(this,name) this.age = age;}// 继承方法SubType.prototype = new SuperType();SubType.prototype.constructor = SubType;复制代码
- 原型式继承
function object(o){ function F(){} F.prototype = o; return new F();}var person = { name:"Nicholas", friends:["Shelby","Court","Van"]};// 实现继承var anotherPerson = object(person);复制代码
- 寄生式继承
function createAnother(original){ var clone = object(original) //原型式继承中的object方法 clone.sayHi = function(){ alert('hi') }; return clone;}var person = { name:'Nicholas', friends:['Shelby','Court','Van']}// 实现继承var anotherPerson = createAnother(person)复制代码
- 寄生组合式继承
function inheriPrototype(subType,superType){ var prototype = object(supeType.prototype); // 继承方法 prototype.constructor = subType; subType.prototype = prototype;}function SuperType(name){ this.name = name; this.colors = ['red','blue','green'];}superType.prototype.sayName = function(){ alert(this.name);}function SubType(name,obj){ // 继承属性 SuperType.call(this,name); this.age = age;}// 继承方法inheritPrototype(SubType,SuperType)复制代码
转载于:https://juejin.im/post/5ac249f76fb9a028cb2dccb9