I'm trying to put a member function from a specific object in a standalone variable, hoping to be able to call the function (on the original object) by simply using the new variable.
So something like this:
var str = "abcdefgh";
var fn = str.indexOf;
console.log(fn("e")); // supposed to output 4
So fn(x)
is supposed to do the same as str.indexOf(x)
. But this doesn't work. Is there another way I can pull this off?
Note that the difficulty here is I want fn to call the function on that specific str
object.
So fn
is to become some sort of closure.
From the You Don't Know JS Series, JS determines the this
in this way
Is the function called with new (new binding)? If so, this is the newly constructed object.
var bar = new foo()
Is the function called with call or apply (explicit binding), even hidden inside a bind hard binding? If so, this is the explicitly specified object.
var bar = foo.call( obj2 )
Is the function called with a context (implicit binding), otherwise known as an owning or containing object? If so, this is that context object.
var bar = obj1.foo()
Otherwise, default the this (default binding). If in strict mode, pick undefined, otherwise pick the global object.
var bar = foo()
Your problem
When you call the indexOf
on the str.indexOf('e')
, JS engine starts to lookup for the context in the function. It sees that you have called the function with .
notation on a string object and refers the context to it. But
when you get the reference of the function and tries to call like fn
, engine starts to search the context (mentioned above) and didn't find anything. Otherwise when you get a function reference outside it loses it's context. So you need to give the context explicitly.
Here I write, that whenever the fn
will be called, the this
inside the function will refer to the str
variable.
var str = "abcdefgh";
var fn = str.indexOf.bind(str);
console.log(fn("e")); // supposed to output 4