开发者

How to get reference to this, when the this is override by calling the method.call(otherObject)?

    var A = function(x)开发者_Go百科{
        var that = this;
        this.a = x;

    }

    A.prototype = {
            init: function(){
                alert(this.a); // as that is not found :s
            }
    };

    var a = new A(1);
    var b = new A(2)
    a.init.call(b);
    // I want to alert number 1, how to do it?

I need this because I use jQuery events.


my sick solution... not so good

I got my question answered but this has some problems, I have to define a local that var and create a closure for every event... sick!

        var that = this;
        this.view.skinAppliedSignal.add(function(){
            that.onSkinApplied();
        });

// then in the onSkinApplied the this is correct. any way not so hacky to get this done?


You cannot do that, in general. The only this that exists when a function runs is the this established by the invocation.

You can "trap" things in a closure when you establish event handlers:

function something() {
  $('.whatever').each(function() {
    var whatever = $(this);
    whatever.find('button').click(function() {
      whatever.hide();
    });
  });
}

In that example, "whatever" is used to save the element from the "each" loop so that the event handlers hooked up to button elements can get access to it.

edit — Based on a comment and the update to the question, it's clear that perhaps what's desired is something like the ".bind()" function that's part of ES5 (and which is supplied by some libraries, like Prototype, Functional, and jQuery). By using "bind", you basically wrap any function of your choice up in another function, such that your function will always be called with this set to some specific object.


Can't be done with a prototype. You could do it this way, however:

var A = function(x){
    var that = this;
    this.a = x;
    this.init = function(){
      alert(that.a);
    }
}

var a = new A(1);
var b = new A(2)
a.init.call(b);​
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜