Javascript 继承调用和应用

Javascript inheritance call and apply

我一直在努力让这个工作一段时间,但一直给我不确定。

function A(first, last){
  this.first = first;
  this.last = last;
}

A.prototype.concat = function(){
  return this.last + this.first;
}

function B(first, last){
  A.call(this, first, last);
  this.type = 'Long';
}

B.prototype.concat = function(){
  A.prototype.concat.apply(this, arguments);
}

var a = new B('A', 'B');
console.log(a.concat());

有人可以帮我弄清楚我错过了什么吗?如果我在 A 上的 concat 方法正在接受一个参数,那么它可以工作,但并非没有它。

你需要做

B.prototype.concat = function() {
  return A.prototype.concat.apply(this, arguments);
//^^^^^^
};

当然,继承的全部意义在于当您不想拦截任何东西时不需要包装函数,但可以调用 inherited 方法直接:

B.prototype.concat = A.prototype.concat;

或更好,使 class 从 A 原型动态继承 all 方法:

B.prototype = Object.create(A.prototype);