Javascript:在函数外获取“this”

Javascript: get `this` outside the function

本文关键字:this 获取 函数 Javascript      更新时间:2023-09-26

是否可以在不使用Javascript的情况下从外部获取函数的this?我知道执行上下文的想法,但我的逻辑是,如果可以将this绑定到一个函数,那么可能有一种方法可以获取它。例如:

var a=function(){}; // let's imagine we have a magic function named `getThisFrom()`
getThisFrom(a); // returns `window` (or nothing, because we haven't used `bind()`)
var obj={};
var b=function(){}.bind(obj);
getThisFrom(b); // returns `obj`

在声明函数a之前,可以将this保存在一个变量中,即var self = this;。然后在a中返回self

var a = function() { var _b = this; return _b; }