简体   繁体   English

JavaScript继承调用并应用

[英]Javascript inheritance call and apply

I have been trying to get this to work for some time now and keeps giving me undefined. 我一直在尝试使它工作一段时间,并一直给我提供不确定的信息。

 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()); 

Can someone help me figure out what I am missing? 有人可以帮我弄清楚我所缺少的吗? If my concat method on A is accepting a parameter, then it works, but not without it. 如果我在A上的concat方法接受一个参数,则它可以工作,但不能没有它。

You would need to do 你需要做

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

but of course the whole point of inheritance is that you don't need a wrapper function when you don't want to intercept anything, but would be able to call the inherited method directly: 但是,当然,继承的全部要点是,当您不想截取任何内容时,不需要包装函数,但是可以直接调用继承的方法:

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

or better, to make the class inherit all methods from the A prototype dynamically: 或更好的方法,是使该类动态继承A原型的所有方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM