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;
任何解釋將不勝感激;謝謝!
那麼答案是比我期待的要簡單得多,你應該使用普通功能。我還研究了箭頭函數以及它們可能對'this'造成的問題。非常需要學習,謝謝! https://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/ – gummyguppy