我是一个来自Ruby背景的新开发人员。最近我一直在JS上努力工作,在新的ES 6中我遇到了一些类继承的问题,我觉得这可能是我对JS的理解的问题,或者是把它和Ruby混在一起了。为了练习,我一直在尝试将Ruby项目转换成JS,但现在我的功能测试失败了。
Failing Feature test when trying to initialize two instances of a class
const STATS = { str:1, dex:1, int:1 }
class Example {
constructor(race, clas) {
this.race = race,
this.clas = clas,
this.stats = this.add(STATS)
}
add(stats) {
if(this.race != 'empty'){
stats.str += this.race.str
stats.dex += this.race.dex
stats.int += this.race.int
}
if(this.clas != 'empty') {
stats.str += this.clas.str
stats.dex += this.clas.dex
stats.int += this.clas.int
}
return stats
}
}
var a = new Example({str: 1, dex:0, int:0}, 'empty');
var b = new Example('empty', {str: 0, dex:0, int:1});
console.log('Should be str:2 dex:1 int:1');
console.log(a.stats);
console.log('Should be str:1 dex:1 int:2');
console.log(b.stats);
我的类具有在构造时更改状态的函数,但问题是每当调用新的类时,它都会保留对前一个变量的更改。这只是我的功能测试中的一个问题,因为这是该类唯一一次被调用两次。
这是指向我的功能测试https://github.com/RyanWolfen7/jsRPG/blob/master/cypress/integration/featureTest/characterFeature_test.js的链接
这就是未通过测试的类https://github.com/RyanWolfen7/jsRPG/blob/master/models/characters/character.js
老实说,我可能会放弃我的项目,重新开始,但我想知道我的问题是什么。我对JS采取了一种面向对象的方法,并将我的ruby项目https://github.com/RyanWolfen7/ruby_rpg转换为JS。我不确定是因为我写错了测试,还是对es-6的工作原理产生了深刻的误解。
我尝试过的东西:
创建新对象
将新创建的对象分配给新类
发布于 2019-02-23 02:44:51
这不是一个继承的问题。事实上,它与OO一点关系都没有。你所看到的是因为javascript中的大多数东西都是引用(指针),但是你编写代码的方式就好像STATS
是一个值。
在您的函数add
中,您可以执行以下操作:
add(stats) {
if(this.race != 'empty'){
// modifying passed in object, not creating new object
stats.str += this.race.str
stats.dex += this.race.dex
stats.int += this.race.int
}
if(this.clas != 'empty') {
// modifying passed in object, not creating new object
stats.str += this.clas.str
stats.dex += this.clas.dex
stats.int += this.clas.int
}
return stats
}
因此,无论您调用add()
多少次,也不管您从哪个Example
实例调用它,您都只是访问和覆盖单个共享STATS
对象。
要在每次函数调用时创建STATS
的新副本,您需要将其复制到新对象。最快的老式方法是将对象序列化为字符串,然后将字符串转换回对象:
add (input) {
var stats = JSON.parse(JSON.stringify(input));
// ...
}
这感觉很难看,但多个基准测试确实表明它是最快的方法。
现代的javascript可以使用Object.assign
来实现这一点。
add (input) {
var stats = Object.assign({},input);
// ...
}
但是,我不知道它是不是更快。您必须自己对其进行基准测试。你可以在谷歌上搜索短语"js clone object"以获取更多信息。
https://stackoverflow.com/questions/54830987
复制相似问题