Reputation: 25
I have a very simple piece of code, and my question is: why is the variable this.wheels
undefined in the getWheel()
private method? I did solved it by passing the context as a parameter in the call inside the public this.spinWheel()
method (writing getWheel.call(this, wheelNumber)
), but it was just I shot after read an article, I wasn't really sure what I was doing because the article wasn't that good.
I know it's something with the function getting the wrong context, but I just can't get the grasp of it (why isn't it getting the right context, if the private function is inside Car
?). Can somebody explain in detail or provide a good resource to read?
JavaScript:
Car = function () {
this.wheels = [1, 2, 3, 4];
function getWheel (wheel) {
this.wheels.some(function (element, index, array) {
if (element == wheel) {
document.getElementById("text").innerHTML = "Wheel " + element + ": vruuum!";
}
});
};
this.spinWheel = function (wheelNumber) {
getWheel(wheelNumber);
};
};
var myCar = new Car();
myCar.spinWheel();
The code is in this JsFiddle.
Any other advice would be welcome, thanks in advance!
Upvotes: 0
Views: 133
Reputation: 8620
In addition to dystroy's solution, you could declare wheels as a var
. Note the small change to getWheel
too.
Car = function () {
var wheels = [1, 2, 3, 4];
function getWheel (wheel) {
wheels.some(function (element, index, array) {
if (element == wheel) {
document.getElementById("text").innerHTML = "Wheel " + element + ": vruuum!";
}
});
};
this.spinWheel = function (wheelNumber) {
getWheel(wheelNumber);
};
};
Upvotes: 0
Reputation: 382150
That's because you don't call it on the right context.
If you add
console.log(this)
at the start of getWheel
, you'll see that this
is window
, the global default context in non strict mode.
A solution would be to change
this.spinWheel = function (wheelNumber) {
getWheel(wheelNumber);
};
to
this.spinWheel = function (wheelNumber) {
getWheel.call(this, wheelNumber);
};
You could also declare in the constructor a variable holding this
and use it directly, or store this.wheels
in a private variable.
Upvotes: 3