开发者

How to set context 'this' to custom object inside function?

开发者 https://www.devze.com 2023-02-19 16:20 出处:网络
Consider code like this: externa开发者_运维知识库l_function = function() { $(this).something2();

Consider code like this:

externa开发者_运维知识库l_function = function() {
    $(this).something2();
}

$('.someclass').live('click', function() {

    $(this).something1();
    external_function(); // wrong way

});

I can add a new method:

external_function = function() {
    $(this).something2();
}

$('.someclass').live('click', function() {

    $(this).something1();
    this.external_function = external_function;
    this.external_function(); // this will work

});

but it seems having overhead to me. Is there a perfect and safe way run external_function with custom context?


You should read about apply and call: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call

0

精彩评论

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

关注公众号