简体   繁体   English

获取JavaScript函数的绑定执行上下文

[英]Get the bound execution context of a javascript function

Let's assume this javascript code 让我们假设这个JavaScript代码

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 ? 现在给定函数bound (例如作为回调),有没有办法检索绑定的上下文-即“ 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. 函数preBound将仅提供其范围,而不会被自身调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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