gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:09:54 25 4
gpt4 key购买 nike

例如,我们有一个函数

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com