javascript实现继承
2020-06-16 本文已影响0人
小枫学幽默
javascript实现继承
原理
-
1 利用函数的
call
方法改变this指向,让子类有父类的属性 -
2 遍历父类的
prototype
中的方法赋值给子类原型,让子类有父类的方法
示例代码
function Dad(name,age){
this.name = name;
this.age = age;
}
//给父类添加方法
Dad.prototype.showName = function(){
console.log("我的名字是" + this.name);
}
//实现子类
function Son(name,age){
Dad.call(this,name,age);
}
for (var key in Dad.prototype){
Son.prototype[key] = Dad.prototype[key];
}
var dd = new Dad("David",40);
var ss = new Son("max",12);
ss.showName(); //我的名字是max