I’ve created the following object:
function Calculator() {
//some code here, including object variables and functions, such as:
this.add = function(x) {
//again, irrelevant code
}
//similar methods
}
var calc = new Calculator();
And then, I tried to do the following:
var met = calc.add;
met(5);
But it didn’t work.
(I’ve checked everything – the variable ‘met’ is of type ‘function’, when I “alert” it to be certain, it alerts the proper string – function(x){...}, etc. But calling met(7) does nothing, while calling calc.add(7) adds the number)
Does anyone know why, or how can I fix it? (Can I fix it?)
Actually, the function inside
addis not irrelevant. The problem you’re having is because howthisbehaves in javascript.When you call it like this:
it’s the same as doing it like this:
Which means that the
thisin met is bound to the global object. So the reason it doesn’t work is because whatever variable you’re trying to add to doesn’t exist in the global object. You can test it simply by declaring that variable in the global object (which for browsers happen to be global variables):If you want to simply alias
addtometbut still operate on thecalcobject you have two options. The first is to make sure thataddis called as a method ofcalc:This is simple and it works as expected. By adding an anonymous function wrapper we can call
addascalc.add()which makesthisbound to calc.The second is as mentioned by @Guffa: use call or apply to point
thisto whatever you want:To understand more about how
thisworks in javascript read this: How does the "this" keyword in Javascript act within an object literal?