0

I am trying to test Map class. My class has a method getCenter() that returns {x:0,y:0}. Also, I want to get {x:1,y:0} calling getRight() and I still want that getCenter() returns {x:0,y:0}.

var assert = require('assert')
    , Map = require('../lib/map')

describe('Map()', function () {
    describe('#getCenter()', function () {
        it('should return [0,0] by default', function () {
            var map = new Map()
            assert.deepEqual({x: 0, y: 0}, map.getCenter())
        })
    })
    describe('#getRight()', function () {
        it('should return [1,0] by default', function () {
            var map = new Map()
            assert.equal(1, map.getRight().x)
            assert.deepEqual({x: 0, y: 0}, map.getCenter())
        })
    })
})

But I am doing something wrong:

var Map = function () {
    this.center = {x: 0, y: 0}
}

module.exports = Map

Map.prototype.getCenter = function () {
    return this.center
}

Map.prototype.getRight = function () {
    var new_position = this.center
    new_position.x += 1
    return new_position
}

I dont want to alter this.center. How can I create new variable? I dont understand the scope of "this.center". I am not changing that variable.

Cœur
  • 37,241
  • 25
  • 195
  • 267
sensorario
  • 20,262
  • 30
  • 97
  • 159

2 Answers2

1

You need to do a copy, instead of just making a reference. Objects and arrays are passed by reference in JS.

var new_position = {x:this.center.x,y:this.center.y};
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
1

Because javascript is based on C and is crazy, assigning a variable to an object actually sets it as a pointer to that object (this also applies to arrays, which is why you need to call var b = a.splice(). So, you'll need to either clone the object (which is bloody difficult to do well: How do I correctly clone a JavaScript object?) or set the new variable to the property directly: return {x: this.center.x + 1, y: this.center.y}

Community
  • 1
  • 1
j-da
  • 188
  • 10