B类继承A类的方法
function A(name) {
this.name = name || 'a';
this.run = function () {
console.info(`${this.name} -- ${this.age} -- run`);
}
}
A.prototype.age = 21;
A.prototype.coding = function () {
console.info(`${this.name} -- ${this.age} -- coding`);
}
var a = new A('aaa');
a.run();
a.coding();
//ES5的继承,B继承A
function B(name) {
//继承A的构造函数,自身属性等
A.call(this, name);
}
//继承A原型链的拷贝,B和A不能公用原型链,否则修改B的原型链也会影响A的原型链,
B.prototype = Object.create(A.prototype);
B.prototype.eat = function () {
console.info(`${this.name} -- ${this.age} -- eat`);
}
var b = new B('bbb');
b.run();
b.coding();
b.eat();
//a.eat(); //报错,eat方法只在B的原型链上
继承代码
function A(){}
//ES5的继承,B继承A
function B(...args) {
//继承A的构造函数,自身属性等
A.call(this, ...args);
}
//继承A原型链的拷贝,B和A不能公用原型链,否则修改B的原型链也会影响A的原型链,
B.prototype = Object.create(A.prototype);