开发者

javascript internal method calls when using jquery

I have a small problem with a object that uses jquery. since jquery overwrites the this pointer I cant call my sub methods without resorting to save the this pointer in a that variable is this a preferred way or is there a better solution? Is there a way to save the this pointer in the object开发者_如何学编程 ( like a class method with another name ) ?

Trying to learn javascript with javascript the good parts but I dont think I understand all the quirks yet :).

//from javscript the good parts
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        var F = function () {};
        F.prototype = o;
        return new F();
    };
}

var Tester = {
    printData: function (text) {
        console.log(text)
    },
    start: function () {
        var that = this;
        jQuery('id').click(function () {
             that.printData('firstColumn')
    });
  }
};

var test = Object.create(Tester)

test.start()

Best Regards Anders Olme guess this is similiar to Overwritten "this" variable problem or how to call a member function?


In general, yes, that's what you have to do.

In this specific case, jQuery provides you some help.

jQuery('id')   // <-- should be #id ?
    .bind('click', { myThing : this }, function (e) {
        e.data.myThing.printData('firstColumn');
    })
;

See the docs for bind(). Internally, jQuery is just doing the exact same thing as you're doing there, so it won't make any significant difference in terms of performance, but it might make your code a bit more manageable.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜