简书原文:https://www.jianshu.com/p/78ce11762f39
前言
1、原型链继承
2、借用构造函数实现继承
3、组合模式继承
4、原型式继承
5、寄生式继承
6、寄生组合式继承
7、代码资源
继承是OO语言中的一个最为人津津乐道的概念。许多OO语言都支持两种继承方式:接口继承和实现继承。接口继承只继承方法签名,而实现继承则继承实际的方法。如前所述,由于函数没有签名,在ECMAScript中无法实现接口继承。ECMAScript只支持实现继承,而且其实现继承主要是依靠原型链来实现的。
function SuperType(name){
this.name = name;
}
SuperType.prototype.sayName = function(){
return this.name;
};
function SubType(age){
this.age = age;
}
//主要代码
SubType.prototype = new SuperType(‘kk‘);
SubType.prototype.sayAge = function(){
return this.age;
};
var instance = new SubType(12);
console.log(instance);
function SuperType(name){
this.name = name;
this.sayName = function() {
return this.name;
}
}
function SubType(name,age){
this.age = age;
this.sayAge = function() {
return this.age;
}
SuperType.call(this,name);
}
var instance = new SubType(‘kk‘,2);
console.log(instance);
function SuperType(name){
this.name = name;
}
SuperType.prototype.sayName = function(){
console.log(this.name);
};
function SubType(name,age){
//继承属性
SuperType.call(this,name);
this.age = age;
}
//继承方法
SubType.prototype = new SuperType(‘gg‘);
SubType.prototype.sayAge = function(){
console.log(this.age);
}
var instance = new SubType("kk",13);
console.log(instance);
function object(o){
function F(){}
F.prototype = o;
return new F();
}
var person = {
name : "kk",
age : 12
};
var extendPerson = object(person);
console.log(extendPerson);
function object(o){
function F(){}
F.prototype = o;
return new F();
}
function createAnother(original){
var clone = object(original);//通过调用函数创建一个新对象
clone.sayHi = function(){//以某种方式来增强这个对象
console.log("hi");
};
return clone;//返回这个对象
}
var person = {
name : "kk",
age : 13
};
var anotherPerson = createAnother(person);
console.log(anotherPerson);
function object(o){
function F(){}
F.prototype = o;
return new F();
}
function inheritPrototype(subType,superType){
var prototype = object(superType.prototype);//创建对象
prototype.constructor = subType;//增强对象
subType.prototype = prototype;//指定对象
}
function SuperType(name){
this.name = name;
}
SuperType.prototype.sayName = function(){
console.log(this.name);
};
function SubType(name,age){
//继承属性
SuperType.call(this,name);
this.age = age;
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge = function(){
console.log(this.age);
};
var instance = new SubType(‘kk‘,15);
console.log(instance);
javaScript实例代码中的extendObject.js中包含本篇博客的代码,包含了JavaScript对象的继承的几种基本方式,希望对读者能有所帮助。
原文:https://www.cnblogs.com/shcrk/p/9255967.html