Javascript: 在函数外获取 `this`
Javascript: get `this` outside the function
是否可以从外部获取函数的 this
而无需在 Javascript 中调用它?我知道执行上下文的想法,但我的逻辑是,如果可以将 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;
。然后returnself
里面a
.
var a = function() { var _b = this; return _b; }
是否可以从外部获取函数的 this
而无需在 Javascript 中调用它?我知道执行上下文的想法,但我的逻辑是,如果可以将 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;
。然后returnself
里面a
.
var a = function() { var _b = this; return _b; }