検索

ホームページ  >  に質問  >  本文

在javascript中, function里this的指向?

在function 里面有个 this,该function分别用apply()和call()调用,this的指向?

PHP中文网PHP中文网2895日前604

全員に返信(3)返信します

  • 伊谢尔伦

    伊谢尔伦2017-04-10 12:49:07

    在js中,调用function的apply()或者call()可以覆盖this原先的指向。但是call()和apply()的用法略有不同,见下面两个例子:

    var myObject = {};
    
    var myFunction = function(param1, param2) {
      this.foo = param1;
      this.bar = param2;
      console.log(this);
    };
    
    myFunction.call(myObject, 'foo', 'bar'); // this 将指向 myObject
    
    console.log(myObject) // 输出 Object {foo = 'foo', bar = 'bar'}
    
    

    用apply()时,参数需要用Array

    var myObject = {};
    
    var myFunction = function(param1, param2) {
      this.foo=param1;
      this.bar=param2;
      console.log(this);
    };
    
    myFunction.apply(myObject, ['foo', 'bar']); // this 将指向 myObject
    console.log(myObject); // 输出 Object {foo = 'foo', bar = 'bar'}
    

    返事
    0
  • 阿神

    阿神2017-04-10 12:49:07

    http://www.css88.com/archives/4431

    返事
    0
  • 天蓬老师

    天蓬老师2017-04-10 12:49:07

    http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html#this

    JavaScript 有一套完全不同于其它语言的对 this 的处理机制。 在五种不同的情况下 ,this 指向的各不相同。

    返事
    0
  • キャンセル返事