Can anyone axplain why the first thing works and the second dont?
function MyObj(val) {
this.value = val;
this.myFunc = function(selector) {
$(selector).html("test: " + this.value);
}
}
foo = new MyObj("tester");
foo.myFunc("#one"); //This works
func = foo.myFunc;
func("#two"); //This doesnt
How? and how can i make it work?
JSFIDDLE
A function’s this in JavaScript isn’t fixed to anything; when you call
something.somefunc()
// or something['somefunc']()
this gets bound to something. When you call a function without an object, this gets bound to undefined (in strict mode) or the global object.
You can get around it by keeping a variable to hold the right this:
function MyObj(val) {
var obj = this;
this.value = val;
this.myFunc = function(selector) {
$(selector).html("test: " + obj.value);
};
}
ECMAScript 5 offers a method on Function.prototype specifically to deal with this (and you should generally put myFunc on MyObj.prototype, too):
var func = foo.myFunc.bind(foo);
func("#two"); // Works now
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With