gpt4 book ai didi

javascript - 如何在javascript中将init参数传递给基类

转载 作者:行者123 更新时间:2023-11-30 17:28:22 26 4
gpt4 key购买 nike

来自 https://stackoverflow.com/a/2107571/494461

function Base (string ) {
this.color = string;
}

function Sub (string) {

}
Sub.prototype = new Base( );


var instance = new Sub ('blue' );

如何将字符串变量提前传递给基类?

最佳答案

像这样调用Base函数

function Base (string) {
this.color = string;
}

function Sub (string) {
Base.call(this, string);
}

使用 Function.prototype.call,您将当前对象设置为 Base 函数调用作为 Sub 中的当前对象。因此,Base 实际上只会在 Sub 对象中创建 color 属性。

此外,对象的原型(prototype)应该只依赖于其他对象的原型(prototype),而不是其他对象。所以,你会想用普通的方式继承

Sub.prototype = Object.create(Base.prototype);

关于javascript - 如何在javascript中将init参数传递给基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23736676/

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