简体   繁体   中英

Get the bound execution context of a javascript function

Let's assume this javascript code

function a (b,c,d) {log(this); return b+c+d;}

a(1,2,3); // logs [Object Window], returns 6
bound = a.bind("hello", 5,6);
bound(7); // logs "hello", returns 18

Now given the function bound (eg as a callback), is there a way to retrieve th bound context - ie "hello", 5, 6 ?

While I don't see a way of directly reading the bound context from a function, you can use it (as another function's execution scope).

/**
 * @param {function} toBeCalled
 * @param {function} preBound
 * @param {array} args
 */
function callOnBoundScope(toBeCalled, preBound, args) {
    toBeCalled.apply(preBound, args);
}

Function preBound will only provide its scope, without being called itself.

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