【问题标题】:this operator in javascriptjavascript 中的 this 运算符
【发布时间】:2010-07-23 17:16:57
【问题描述】:

假设我有像

这样的 JavaScript 代码
      myClass = function(){
          function doSomething(){
              alert(this); // this1 
          }
      } 
      alert(this); //this2

这两个“this”对象指的是什么??

【问题讨论】:

    标签: javascript this


    【解决方案1】:

    全局执行上下文中的this值,指的是全局对象,例如:

    this === window; // true
    

    对于函数代码,这真的取决于你如何调用函数,例如,this 值在以下情况下被隐式设置:

    调用没有基础对象引用的函数

    myFunc();
    

    this 值也将引用全局对象。

    调用绑定为对象属性的函数

    obj.method();
    

    this 值将引用 obj

    使用new 运算符

    new MyFunc();
    

    this 值将引用从MyFunc.prototype 继承的新创建的对象。

    此外,您可以在调用函数时显式设置该值,使用 callapply 方法,例如:

    function test(arg) {
      alert(this + arg);
    }
    test.call("Hello", " world!"); // will alert "Hello World!"
    

    callapply 之间的区别在于apply 可以正确传递任意数量的参数,使用数组或arguments 对象,例如:

    function sum() {
      var result = 0;
      for (var i = 0; i < arguments.length; i++) {
        result += arguments[i];
      }
      return result;
    }
    
    var args = [1,2,3,4];
    sum.apply(null, args); // 10
    
    // equivalent to call
    sum(1,2,3,4); // 10
    

    如果callapply的第一个参数值为nullundefined,则this值将引用全局对象。

    (请注意,这将在未来发生变化,在 ECMAScript 5 中,callapply 无需修改即可传递 thisArg 值)

    【讨论】:

      猜你喜欢
      • 2015-01-16
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 2015-01-26
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多