Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS cannot access object value from different function

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

like image 381
kajacx Avatar asked Feb 05 '26 21:02

kajacx


1 Answers

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
like image 197
Ry- Avatar answered Feb 09 '26 01:02

Ry-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!