代码之家  ›  专栏  ›  技术社区  ›  Sam

轻松设置“this”变量?

  •  133
  • Sam  · 技术社区  · 17 年前

    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 回复  |  直到 8 年前
        1
  •  228
  •   Remi Guan cdlane    10 年前

    JavaScript中为所有函数定义了两种方法, call() apply()

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

    这些函数所做的是调用它们所调用的函数,并为 参数到 .

    var myFunction = function(){
        alert(this.foo_variable);
    }
    myFunction.call( document.body );
    
        2
  •  57
  •   sth    15 年前

    call :

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

    这叫 myFunction 具有 this 着手 obj

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

    myFunction.apply(obj, [arg1, arg2, ...]);
    
        3
  •  19
  •   pimvdb    15 年前

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

    var bound = func.bind(someThisValue);
    
    // ... later on, where someThisValue is not available anymore
    
    bound(); // will call with someThisValue as 'this'
    
        4
  •  1
  •   Daniel Sokolowski    9 年前

    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();
    
        5
  •  1
  •   Willem van der Veen    7 年前

    this

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

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

    调用/应用和绑定之间的区别:

    • call apply 它们的相似之处在于 立即调用函数 )
    • bind 不同于 申请 返回一个新函数 价值

    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');