(三十七)JavaScript常用继承方式(上)
1:原型链继承
function Super() {
this.text = 'Hello';
}
Super.prototype.getSuperText = function() {
return this.text;
}
function Sub() {
this.subText = 'Word';
}
Sub.prototype = new Super();
const instance = new Sub();
console.log(instance);
优点 - 简单易操作
缺点 - 对引用类型数据操作会互相影响
function Super() {
this.value = [1, 2, 3, 4];
}
Super.prototype.getSuperValue = function() {
return this.value;
}
function Sub() {
this.subText = 'Word';
}
Sub.prototype = new Super();
const instance1 = new Sub();
const instance2 = new Sub();
instance1.value.push(5);
console.log(instance2.value);