例如,我们有一个函数
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)中的函数。哪种方法最好?
最佳答案
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/