开发者

How to access instance property in an instance method when the method is being passed into an another function?

开发者 https://www.devze.com 2023-03-03 00:07 出处:网络
I know in the code below it will print out undefined if I click on the button, because this.field becomes within the context of the button and not Container. My question is how can I access this.field

I know in the code below it will print out undefined if I click on the button, because this.field becomes within the context of the button and not Container. My question is how can I access this.field of Container when this.func is passed into another function, which is a different context scope than Container.

function Container(){
    this.field = 'field';

    $('button').click(this.func);
}

Container.prototype.func = function(){
   console.log(this.field);
}

I know I can do this, but is there a better way? Because I'd rather define the methods outside the constructor so I won't clutter it.

function Container(){
    var thisObj = this;
    this.fie开发者_如何学Gold = 'field';

    $('button').click(function(){ console.log(thisObj.field) });
}


Pass the object reference in as the event data:

function Container(){
    this.field = 'field';

    $('button').click(this, this.func);
}

Container.prototype.func = function(e){
   console.log(e.data.field);
}

See here: http://jsfiddle.net/gilly3/nwtqJ/


How about passing an anonymous function?

function Container(){
    this.field = 'field';
    var self = this;

    $('button').click(function() {
        self.func()
    });
}

You have not many choices here...

jQuery makes it a bit easier for you and offers $.proxy:

 $('button').click($.proxy(this.func, this));
 // or
 $('button').click($.proxy(this, 'func'));


I'd just like to point out that, generally speaking, you should avoid thinking of the 'this' variable as having any resemblance to the one in java. You clearly understand that, but it always bears repeating. Since javascript's this always points to the object on which you called the function, your passing of an instance function to another object to use as its onclick leads to confusion. I don't know what you intend to do in the instance method itself, but there is no reason why an onclick handler should be an instance method of another object. If it's access to the members you want, they're public, so no need to have it be an instance method. If the work to be done relates exclusively to the Container object, then the onclick should possibly be a separate function that would have a refernce to the container and call the instance method.

0

精彩评论

暂无评论...
验证码 换一张
取 消