首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >ES 6 JS的类继承问题及其失败测试

ES 6 JS的类继承问题及其失败测试
EN

Stack Overflow用户
提问于 2019-02-23 00:07:53
回答 1查看 58关注 0票数 0

我是一个来自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的工作原理产生了深刻的误解。

我尝试过的东西:

创建新对象

将新创建的对象分配给新类

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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"以获取更多信息。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54830987

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档