手写有关js继承

1、写一个原型链继承

function SuperType() {
  this.property = true;
}
SuperType.prototype.getSuperValue = function() {
  return this.property;
}
function SubType() {
  this.subproperty = false;
}
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function() {
  return this.subproperty;
}
var instance = new SubType();
console.log(instance.getSuperValue());  // true

2、写一个组合继承

function SuperType(name) {
  this.name = name;
}
SuperType.prototype.sayName = function() {
  alert(this.name);
}
function SubType(name, age) {
  SuperType.call(this, name);
  this.age = age;
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function() {
  alert(this.age);
}

下面两步也可等同于:

SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype = Object.create(SuperType.prototype)

其内部实际上实现了三步:

  1. 创建对象:var prototype = object(SuperType.prototype);
  2. 增强对象:prototype.constructor = SubType;
  3. 指定对象:SubType.prototype = prototype;

猜你喜欢

转载自blog.csdn.net/weixin_43912756/article/details/108326789
今日推荐