Why can't jQuery methods be saved?

It seems you cannot do this with jQuery:

f = $("#someElement").text
f("Bar!")

On chrome, this gives me this error: "TypeError: Object [object global] does not have a method of" empty ""

Why is this?

http://jsfiddle.net/bdN4z/

+3
source share
2 answers

The function textuses an internal value this.

The value thisdepends on how you call the function.

When you call $("#someElement").text(), you call it in the context of the jQuery instance. JQuery instances have a method empty.

When called, f()you call it in the context of the default object ( window). windowdoesn't have a method empty.

+4
source

...

?

someElement = $("#someElement");
f = someElement.text.bind(someElement);
f("Bar!")
+2

All Articles