1

I have the following JavaScript code:

function PatternField(id, name, pattern) {
    ...

    this.check = function () {
        var field = this.elem.val();
        ...
    };

    this.elem.keyup(this.check);
    this.elem.change(this.check);
}

When the execution comes to check function var field = this.elem.val(); it turns out that this points to elem rather than actual object. How can I access real this from inside this object function?

2
  • Just out of curiosity, if this is referring to the element already why not use this.value inside the check method? Commented Nov 25, 2013 at 21:58
  • @FrançoisWahl, good idea :) I just wanted to know how to solve this problem in general. Commented Nov 26, 2013 at 14:51

2 Answers 2

6
this.check = function() {
    var field = this.elem.val();
    ...
}.bind(this);

The important part being bind(this) which controls the scope of the function once it is invoked/called (note that the function is not invoked immediately when using bind, you are manipulating the definition, if you will...); in this case, retaining the scope of PatternField. Check the docs regarding bind at MDN.


In other words (in regards to some comment that magically deleted itself):

It makes sure that the scope of this.check (when called) will be whatever is passed to the first parameter of bind, overriding whatever might naturally occur. If the you want this to reference PatternField within the this.check method, the bind method of Function will enable this capability.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I didn't see that OP was passing this.check as an event handler.
@BlueSkies np, i hope the extra explanation helps too. :)
4

Like @zamnuts answered, you can use the ES5 bind method.

But if you want to do it the old way, i.e., supporting old browsers without a polyfill, you can use:

var that = this;
this.check = function () {
    var field = that.elem.val();
    ...
};

3 Comments

Yes, this closure method is the safest in terms of legacy support. If older compatibility is of concern, this is your best bet.
@zamnuts: Not only that but it also preserves the actual this as it is passed through the event. This way you can access this within the scope as well (assuming it is of use) as well as that to get access to your object.
@FrançoisWahl yea no doubt! however, in most cases a reference to the object is available within the callback arguments, and switching the value of this could be confusing, for example in a series of prototype definitions, where one would assume this would always be the primary subject.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.