javascript - JS继承原型(prototype)时如何传递参数?

标签 javascript parameter-passing prototype prototypal-inheritance

例如,我们有一个函数

function FirstFunction(name, surname){
    this.name = name;
    this.surname = surname;
    ...
}

我们的原型(prototype)中有一些函数,还有另一个函数“SecondFunction”,它有自己的原型(prototype)。当我想继承原型(prototype)时我会写

SecondFunction.prototype = Object.create(FirstFunction.prototype);

现在,当我尝试使用创建新变量时

var newVariable = new SecondFunction();

我想传递 FirstFunction 中列出的参数“name”和“surname”,以便能够使用 FirstFunction 原型(prototype)中的函数。哪种方法最好?

最佳答案

我认为正确的方法是使用 callapply :

function FirstFunction(name, surname){
    this.name = name;
    this.surname = surname;
}

function SecondFunction(name, surname) {
  FirstFunction.call(this, name, surname)
}
SecondFunction.prototype = Object.create(FirstFunction.prototype);


var newVariable = new SecondFunction('Harry', 'Potter');
console.log(newVariable);

您可以引用this article这解释了它。

关于javascript - JS继承原型(prototype)时如何传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54788415/

相关文章:

javascript - 如何从原型(prototype) "class"中调用原型(prototype)函数?

javascript - 在原型(prototype)与构造函数中声明属性?优点和缺点?

javascript - 哪些参数最好存储在localStorage中?

javascript - Google map V3.0 地点 Api

javascript - 搜索 Google 云端硬盘中子文件夹内的文件

ios - 快速函数调用中是否有必需的参数顺序

javascript - 访问传递给原型(prototype)函数的值

javascript - 如何使用 Angular js 在 Google Analytics 中设置 siteSpeedSampleRate 值

Java:传递双向链表的数组列表作为参数

c++ - 我可以在 C++ 中通过引用传递多少个参数,而不会出现异常行为