Actually, the function inside add
is not irrelevant. The problem you're having is because how this
behaves in javascript.
When you call it like this:
met(5);
it's the same as doing it like this:
window.met(5); // assuming browsers
Which means that the this
in 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):
var foo = {
i = 0,
incr = function(){ return ++this.i }
}
foo.incr(); // this works as expected
// now assign foo.incr to the global object:
var inc = foo.incr;
inc(); // this fails because window.i doesn't exist
// create i in window
i =0;
inc(); // now this works, maybe a bit unexpected
If you want to simply alias add
to met
but still operate on the calc
object you have two options. The first is to make sure that add
is called as a method of calc
:
var met = function(x) { return calc.add(x) };
met(5);
This is simple and it works as expected. By adding an anonymous function wrapper we can call add
as calc.add()
which makes this
bound to calc.
The second is as mentioned by @Guffa: use call or apply to point this
to whatever you want:
var met = calc.add;
met.call(calc,5);
To understand more about how this
works in javascript read this: How does the "this" keyword in Javascript act within an object literal?