简体   繁体   中英

Call javascript function with bind

I have the function:

$(this.myObject).click(A.bind(this));
function A(){
     //  stuff here
}

I want to call from within a second function (binding this).

$(this.myOtherObject).click(B.bind(this));
function B(){
      A();             //  works but does not bind
      A.bind(this);    //  does not work
}

How can I do this?

您想使用call(this)而不是 bind() 因为 bind() 只是返回该方法。

A.call(this)
function B(){
    A();             //  works but does not bind
    A.bind(this);    //  does not work
}

bind is for creating a new function bound to a context (see bind documentation ). If you go that way, you would need to call the new function :

A.bind(this)();

However, you should rather use call method or apply method which will directly call the function with a specific context :

A.call(this);
A.apply(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM