2017-06-17 87 views
0

这是一个使用摩卡来探索TDD的简单应用程序。该应用程序将获得两套扑克牌手并确定获胜的牌。实例化后返回undefined的属性值

我有一些问题,找出为什么我的值返回undefined后调用对象上的函数。实例化后,各个变量正确存储;但使用函数检索这些较早值的变量将返回它们为未定义的值。一般来说,我对节点/网络开发不熟悉,我能想到的唯一可能是sync/async?

的代码可以在github here

在这里找到是终端:

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' 

const app = require('express'), 
     mocha = require('mocha'), 
     chai = require('chai') 

let expect = chai.expect 

let card = require('../app/card.js') 

describe('Test card module',() => { 

    const myCard = new card.card('s', 1) 
    console.log(JSON.stringify(myCard)) 

    it('card is not null',() => { 

    expect(myCard).is.not.null 
    }) 

    it('has all arguments valid and present',() => { 

    expect(myCard).has.property('suit') 
    expect(myCard).has.property('val') 
    }) 


    it('has image value property',() => { 

    expect(myCard).has.property('getCardImage') 
    }) 

    it('has valid image path',() => { 

    expect(myCard.getCardImage).to.equal('images/s/1.img') 
    }) 


}) 

和最后应用文件:

'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; 

任何解释将不胜感激;谢谢!

回答

0

你需要调用函数

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 
} 
+0

那么答案是比我期待的要简单得多,你应该使用普通功能。我还研究了箭头函数以及它们可能对'this'造成的问题。非常需要学习,谢谢! https://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/ – gummyguppy