轻松设置“this”变量?

IT技术 javascript variables scope this
2021-01-29 13:40:39

我对 Javascript 有很好的理解,只是我想不出设置“this”变量的好方法。考虑:

var myFunction = function(){
    alert(this.foo_variable);
}

var someObj = document.body; //using body as example object
someObj.foo_variable = "hi"; //set foo_variable so it alerts

var old_fn = someObj.fn;   //store old value
someObj.fn = myFunction;   //bind to someObj so "this" keyword works
someObj.fn();              
someObj.fn = old_fn;       //restore old value

没有最后 4 行,有没有办法做到这一点?这很烦人......我尝试绑定一个匿名函数,我认为它很漂亮很聪明,但无济于事:

var myFunction = function(){
    alert(this.foo_variable);
}

var someObj = document.body;        //using body as example object
someObj.foo_variable = "hi";        //set foo_variable so it alerts
someObj.(function(){ fn(); })();    //fail.

显然,将变量传递给 myFunction 是一种选择……但这不是这个问题的重点。

谢谢。

5个回答

JavaScript 中为所有函数定义了两种方法call(), 和apply()函数语法如下所示:

call( /* object */, /* arguments... */ );
apply(/* object */, /* arguments[] */);

这些函数所做的是调用它们被调用的函数,将对象参数的值分配this

var myFunction = function(){
    alert(this.foo_variable);
}
myFunction.call( document.body );
另一个有用的方法是 .bind()
2021-03-31 13:40:39
此外,如果您使用的是 jQuery,则可以使用,$.proxy(function, element)以便无论何时调用该函数,它都将位于 element 的上下文中。api.jquery.com/jquery.proxy
2021-04-12 13:40:39

我认为您正在寻找call

myFunction.call(obj, arg1, arg2, ...);

这就要求myFunctionthis设置为obj

还有稍微不同的 method apply,它将函数参数作为数组:

myFunction.apply(obj, [arg1, arg2, ...]);
请参阅 ECMAScript 语言规范中的第 15.3.4.3、15.3.4.4 和 10.1.8 节:ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
2021-04-11 13:40:39

如果您想将this“存储”到一个函数中,以便以后可以无缝调用它(例如,当您无法再访问该值时),您可以bind(尽管并非在所有浏览器中都可用):

var bound = func.bind(someThisValue);

// ... later on, where someThisValue is not available anymore

bound(); // will call with someThisValue as 'this'
仅供参考,bind在 IE9+、FF4+、Safari 5.1.4+ 和 Chrome 7+ (来源)中显然可用您还可以直接在匿名函数上调用 bind:var myFunction = function(){ /* this = something */ }.bind(something);
2021-03-30 13:40:39

我对如何绑定的搜索this把我带到了这里,所以我发布了我的发现:在“ECMAScript 2015”中,我们还可以使用箭头函数在词法上将其设置为。

请参阅:https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

代替:

function Person() {
  setInterval(function growUp() {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    this.age++;
  }.bind(this), 1000);
}

我们现在可以这样做:

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();

this在javascript中设置关键字。

Javascript 有 3 种内置方法可以this方便地设置关键字。它们都位于Function.prototype对象上,因此每个函数都可以使用它们(因为每个函数都通过原型继承从该原型继承)。这些功能如下:

  1. Function.prototype.call():此函数将您要使用的对象this作为第一个参数。然后其余的参数是被调用函数的相应参数。
  2. Function.prototype.apply():此函数将您要使用的对象this作为第一个参数。然后第二个参数是一个数组,其中包含被调用函数的参数值(数组的第一个元素是函数的第一个参数,数组的第二个参数是函数的第二个参数等)。
  3. Function.prototype.bind():此函数返回一个新函数,它具有不同的值this它将您要设置为this的对象作为第一个参数,然后返回一个新的函数对象。

call/apply 和 bind 的区别:

  • call并且apply相似之处在于它们立即调用函数(具有预定义的值this
  • bind不同于callapply在事实上,这个函数返回一个新的功能具有不同的结合this值。

例子:

const thisObj = {
  prop1: 1,
  prop2: 2,
};

function myFunc(arg1, arg2) {
  console.log(this.prop1, this.prop2);
  console.log(arg1, arg2);
}

// first arg this obj, other arguments are the  
// respective arguments of the function
myFunc.call(thisObj, 'Call_arg1', 'Call_arg2');

// first arg this obj, other argument is an array which  
// are the respective arguments of the function
myFunc.apply(thisObj, ['Apply_arg1', 'Apply_arg2']);


// the bind method returns a new function with a different
// this context which is stored in the newMyFunc variable
const newMyFunc = myFunc.bind(thisObj);

// now we can call the function like a normal function 
newMyFunc('first', 'second');