gpt4 book ai didi

带有参数的 Javascript "class"扩展名?

转载 作者:行者123 更新时间:2023-11-29 21:50:24 24 4
gpt4 key购买 nike

我想从现有类“扩展”一个新类,并包含它的方法和参数构造。

System = function(name, hp){
this.name = name;
this.hp = [];
this.setHP = function(hp){
this.hp[0] = hp;
this.hp[1] = hp;
}
this.setHP(hp);
}

Weapon = function(name, hp){
System.call(this);
}

Weapon.prototype = new System(name, hp);
Weapon.prototype.constructor = Weapon;


var gun = new Weapon("Gun", 10); // undefined name, hp
var hangar = new System("Hangar", 10); // works

所以,就我所知,有人显然是错的。有人可以给我建议吗?

最佳答案

您需要在调用中传递参数:

System.call(this, name, hp);

另外,请注意 Weapon.prototype = new System(name, hp); 可能有副作用,最好使用:

Weapon.prototype = Object.create(System.prototype);

如果您需要支持古老的浏览器,您可以找到 Object.create 的 polyfill。

关于带有参数的 Javascript "class"扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29556237/

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