一、原型链继承
实现方法:设置B.prototype = new A即可(其中B为子类,A为父类)
特点:它把父类中的私有属性和共有属性都继承到了子类的原型链上(new A得到一个实例对象,该对象具有构造函数A的私有和公有属性)
核心:原型链继承方式并不是将父类的所有属性克隆一份给了子类,而是在父类和子类之间建立了原型链的连接,如果子类需要使用父类的方法,则通过原型链一级一级的向上查找即可
function A() {
this.x = 100
}
A.prototype.getX = function(){
console.log(this.x)
}
function B() {
}
B.prototype = new A;
B.prototype.constructor = B
二、call方法实现继承
特点:把父类私有的属性和方法克隆一份给子类的私有
function A() {
this.x = 100
}
A.prototype.getX = function(){
console.log(this.x)
}
function B() {
//让A方法执行并且将A中的this变为B的实例,这里即实例n,相当于执行了n.x = 100
A.call(this)
}
var n = new B;
三、冒充对象继承
特点:把父类公有的和私有的克隆一份给子类的私有的
function A() {
this.x = 100
}
function B() {
var temp = new A;
for (var key in temp) {
this[key] = temp[key];
}
temp = null;
}
四、混合模式继承(原型链+call)
特点:可以继承父类的私有和公有属性,但是父类私有属性会同时出现在子类公有和私有属性中
function A() {
this.x = 100
}
A.prototype.getX = function(){
console.log(this.x)
}
function B() {
A.call(this);
}
B.prototype = new A;
B.prototype.constructor = B
五、继生组合
为了解决第四种方法中父类的私有属性同时出现在子类的私有和公有属性上的问题而诞生的
function A() {
this.x = 100
}
A.prototype.getX = function(){
console.log(this.x)
}
function B() {
A.call(this);
}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B
补充:Object.create方法的兼容写法
function myObjectCreate(o) {
function Fn() {
}
Fn.prototype = o;
return new Fn
}
六、中间类继承法
这里我们以一个求平均数的方法为例
function avg() {
//由于arguments只是一个类数组,不是真正的数组,所以不能使用数组中的方法,我们借助call方法来借助数组的方法
Array.prototype.sort.call(arguments, function (a, b) {
return a - b;
})
Array.prototype.pop.call(arguments)
Array.prototype.shift.call(arguments)
return (eval(Array.prototype.join.call(arguments, '+')) / arguments.length).toFixed(2)
}
现在我们使用中间类继承法就方便很多
function avg() {
arguments.__proto__ = Array.prototype
arguments.pop();
arguments.shift();
return (eval(arguments.join.call(arguments, '+')) / arguments.length).toFixed(2)
}
注意:这种方法不兼容IE,因为IE不支持获取__proto__
该文由珠峰培训的视频课程总结的笔记