如何为每个函数动态绑定“this”

How can I bind dynamically "this" for each function?

本文关键字:动态绑定 this 函数      更新时间:2023-09-26

我正在寻找一种将this绑定到每个function的方法。

我还尝试创建一个执行上下文(包装器);这不适用于包含的脚本/模板,其中包含<script> -Tags

以下是我想要的例子。

例子:

//Added "this" to each function: "this_"
//Inside <script src='external_source_link'></script>
function a() { alert(this) }
a(); //result: "this_"

我需要一种方法来动态检测创建的任何函数。在发生这种情况(创建函数)之前,我应该有可能向函数或函数体添加一些东西(参数和参数)

function a() { } //my dynamically manipulation: a = a.bind("this_");

这不能是包装器{ }因为 im 还使用 <script> -Tags 从外部资源加载脚本

<script src="external_source_link"></script>

所以也许有一个操纵Funtion.prototype的解决方案......

如果我理解得很好,你需要一个proxythis.

如果你愿意,你可以这样做:

function caller(){
    proxy(this,callee, "hello");
}
function callee(testStr){
    console.log("this: ", this);
    console.log("testStr: ", testStr);
}
function proxy(thisToBind, fnToCall){
    var args = arguments;
    if (args.length > 2) {
        delete args[0];
        delete args[1];
    }
    else {
        args = undefined;
    }
    fnToCall.call(thisToBind, args);
}
caller();

如果你想全局覆盖原始Function.prototype.constructor(对于所有功能),恐怕你不能。但是,请查看Mozilla参考