Reputation: 679
I'm trying to create a (pure) constructor function and a QUnit test for it:
//app.js
function myFunc(param1, param2) {
this.param1 = param1;
this.param2 = param2;
return this;
}
//test.js
QUnit.test("should return a string and a number", function(assert) {
assert.ok(myFunc("some-string", 4545435234), "a string and a number were returned");
});
The code runs and passes my test until I add "use strict"
to app.js
. Then QUnit displays the following fail message:
1. Died on test #1 at http://some/url/:1:1: Cannot set property 'param1' of undefined
Source: TypeError: Cannot set property 'param1' of undefined
I can get both the code to work and the test to pass if I return the myFunc
parameters as an array:
function myFunc(param1, param2)) {
return [param1, param2];
}
But that just doesn't seem right. I get that this has something to do with var hoisting but I'm not clear about it.
Thanks in advance. ...
Upvotes: 0
Views: 148
Reputation: 13273
In strict mode JavaScript functions are not given the default context (this
), thus you must provide the context. Once way to do this is through the new
keyword. If you change your assertion to the following I think this will work:
assert.ok(new myFunc("some-string", 4545435234), "a string and a number were returned");
Upvotes: 1