Node.js 实例化后返回未定义的属性值

Node.js 实例化后返回未定义的属性值,node.js,ecmascript-6,mocha.js,undefined,chai,Node.js,Ecmascript 6,Mocha.js,Undefined,Chai,这是一个使用摩卡探索TDD的简单应用程序。该应用程序将被赋予两套扑克手和定义获胜的手 在我调用对象上的函数后,我发现了一些问题,无法解释为什么我的值返回undefined。实例化后,各个变量正确存储;但是使用函数检索这些早期值的变量返回未定义值。一般来说,我不熟悉节点/web开发,我唯一能想到的可能是sync/async 代码可以在github上找到 这是终点站: images/undefined/undefined.img {"suit":9,"val":1,"img":"images/und

这是一个使用摩卡探索TDD的简单应用程序。该应用程序将被赋予两套扑克手和定义获胜的手

在我调用对象上的函数后,我发现了一些问题,无法解释为什么我的值返回undefined。实例化后,各个变量正确存储;但是使用函数检索这些早期值的变量返回未定义值。一般来说,我不熟悉节点/web开发,我唯一能想到的可能是sync/async

代码可以在github上找到

这是终点站:

images/undefined/undefined.img
{"suit":9,"val":1,"img":"images/undefined/undefined.img"}


  Test card module
    ✓ card is not null
    ✓ has all arguments valid and present
    ✓ has image value property
    1) has valid image path

  3 passing (13ms)
  1 failing

  1) Test card module has valid image path:
     AssertionError: expected [Function] to equal 'images/s/1.img'
      at Context.<anonymous> (test/cardTest.js:35:36)
最后是应用程序文件:

'use strict'

function card(suit, val) {

  this.suit = suit
  this.val = val
  this.img = this.getCardImage()
}

card.prototype.getCardImage = () => {

  console.log('images/' + this.suit + '/' + this.val + '.img')
  let location = 'images/' + this.suit + '/' + this.val + '.img'

  return location
}

exports.card = card;

如有任何解释,将不胜感激;谢谢大家!

您需要调用该函数

expect(myCard.getCardImage()).to.equal('images/s/1.img')
您应该使用普通函数,因为其中包含动态上下文
this

card.prototype.getCardImage = function() {

  console.log('images/' + this.suit + '/' + this.val + '.img')
  let location = 'images/' + this.suit + '/' + this.val + '.img'

  return location
}

答案比我预想的要简单得多。我还研究了箭头函数以及它们可能对“this”造成的问题。要学的东西太多了,谢谢!
card.prototype.getCardImage = function() {

  console.log('images/' + this.suit + '/' + this.val + '.img')
  let location = 'images/' + this.suit + '/' + this.val + '.img'

  return location
}