【问题标题】:The scope of "this"“这个”的范围
【发布时间】:2013-05-25 18:52:04
【问题描述】:

我有一个简单的对象,通过调用这个对象的函数我不明白this的概念(范围)。

为什么在最后一个变体 (3) 中调用 show()(在没有父对象的内部对象中使用函数 show())结果是“这是全局的”而不是内部变量 title("Color Picker")

我有一个模糊的想法,在定义全局变量show之后调用函数popup.show()this指的是全局对象。这是逻辑解释吗?

代码:http://jsbin.com/otuzac/1/edit

var title="'This' is global";

var popup={
    dom_element:("#popup"),
    title      :"Color Picker",
    prev_color :'#fff',
    set_color  : function(color){
        color=color || this.prev_color;
        //set the color
        return color;
    },
    show       :function(){
        return("showing  "+this.title);
    }       
};

var show=popup.show();

//Case 1: var show=popup.show()
alert(show);  //output "Color Picker"

//Case 2: var show=popup.show()
alert(popup.show());  //output "Color Picker"

//Case 3: var show=popup.show !!! (no parent.)
alert(show());  //output "This is global"

【问题讨论】:

标签: javascript


【解决方案1】:

this 是什么取决于您如何调用使用this 的函数。

1。作为函数调用

functionName();

在这种情况下,this 将始终引用全局对象(通常是 window 对象)。

Example

a = 2;
function XY(a) {
    this.a = a;
    this.b = function () {
        func();
    };

    function func () {
        console.log(this.a);
    }
}

var xy = new XY(1);
xy.b(); //2

备注

  • 这个例子有点构建,但是请注意,函数func是通过简单的写func();来调用的。因此,即使您的函数位于构造函数 (XY) 中并从作为方法调用的函数中调用(参见第 3 点),this 仍然指的是全局对象。

2。使用新关键字调用

var obj = new functionName();

在这种情况下,this 将引用新创建的对象。

Example

a = 2;
function XY(a) {
    this.a = a;
}

var xy = new XY(1);
console.log(xy.a); //1

3。作为方法调用

obj.functionName();

在这种情况下,this 将引用包含您正在调用的函数的对象。

Example

a = 2;
var xy = {
    a: 1,
    func: function() {
        console.log(this.a);
    }
}
xy.func(); //1

4。使用apply拨打电话

functionName.apply(thisObj, argArray);

在这种情况下,this 将是 new Object(thisObj)thisObj 是函数 apply 的第一个参数。

Example

function xy (a,b) {
    console.log(this);
}

xy.apply({f:3}, [1,2]); //Object {f: 3} 
xy.apply("hello", [1,2]); //String {0: "h", 1: "e", 2: "l", 3: "l", 4: "o"}

5。由事件处理程序调用

正如用户 Mifeet 所建议的,事件也会改变 this 的上下文:

事件是一种单独的主题。它们不是 EcmaScript 的一部分,通常由不同的浏览器以不同的方式处理。尽管如此,关于this 的差异很小,据我所知,IE > 8 不存在。

this 将引用触发事件的 DOM 元素,除非您使用内联事件处理程序。在这种情况下,this 将引用全局对象。

Example

<button id="1" onclick="clickit()">click me</button>  <!-- 0 -->
<button id="2">click me</button>
<button id="3">click me</button>
<script>
var button1 = document.getElementById("1");
var button2 = document.getElementById("2");
var button3 = document.getElementById("3");

id = "0";

window.clickit = function(){
    console.log(this.id);
};


button2.onclick = clickit; //2
button3.addEventListener("click", clickit, false); //3
</script>

对事件的评论

  • 版本 9 之前的 Internet Explorer 不支持 addEventListener,但支持 attachEvent。使用此函数还会导致 this 引用全局对象。
  • this,直接在 HTML 标签内,将引用代表该标签的 DOM 元素。因此&lt;button id="1" onclick="clickit(this)"&gt;click me&lt;/button&gt; 会将DOM 元素传递给clickit 事件处理程序。

回到你的案子

在前两种情况下,您将函数作为方法调用,在最后一种情况下,您将其作为函数调用。这就是为什么在最后一种情况下,this 指的是全局对象。

编辑

我最近在 StackOverflow 上看到了一个非常相似的问题的答案。不幸的是,我再也找不到它了,所以我决定自己发布一个答案。但是,如果有人知道我的意思是什么答案,请发表评论,我很乐意在我的答案中添加指向原始答案的链接。

【讨论】:

  • 谢谢,很好的解释;)
  • 事件处理程序呢,不是特例吗?
  • 问题:在您的第一种情况下,函数实际上是一种方法。我错过了什么吗?!除了您使用创建对象的 new 运算符调用它之外,必须是该对象的方法...
  • @Alexis 函数func 被作为函数调用。它在另一个函数中被调用,即作为方法调用。我只是想表明你在哪里定义你的函数和在哪里调用它并不重要,只要你通过写func()将它作为一个函数调用,该函数内部的this对象将引用全局对象。
  • @Mifeet 是的,你是对的,这将是第五种情况,其中this 关键字指的是事件监听器被分配到的 DOMElement。
【解决方案2】:

在你的 案例 1: var show=popup.show() 正在调用 popup 对象中定义的函数 show。 并且显示函数有这个对象引用弹出对象并且弹出对象有它自己的标题变量,它正在调用显示函数。这就是为什么显示“颜色选择器”

案例 2: 这也与案例 1 类似,您在不使用变量的情况下调用 show 函数。所以同样的输出。

案例 3: 在案例 1 和案例 2 中,您调用函数 show 时没有引用任何对象。 所以默认它采用对象 od 文档。在文档中,title 的值是 "'This' is global",因此它会向您显示结果 "'This' is global"。这是指文档对象。

希望这对你有帮助。

【讨论】:

    【解决方案3】:

    正如其他人所解释的,在前两种情况下,您在popup 对象上调用函数,因此this 指的是popup。在第三种情况下,您单独调用函数,而不是在对象上调用,因此this 指的是全局范围(window)。另外,在您的示例中,您不能使用alert(show());,因为这里的show 不是函数,而是字符串。

    如果你想得到想要的结果,你可以使用下面的模式(被许多框架使用,例如 jQuery):

    var title="'This' is global";
    (function() {
        var popup = { 
            dom_element:("#popup"),
            title      :"Color Picker",
            prev_color :'#fff',
            set_color  : function(color){
                color=color || this.prev_color;
                //set the color
                return color;
            },
            show       :function(){
                return("showing  " + popup.title); // refer to the local variable popup instead of this
            }       
        };
        window.popup = popup; // add the (now initialized) local variable popup to the global scope
    })(); // execute immediately
    
    var show=popup.show();
    var showFn = popup.show; // You cannot use the result of popup.show() as a function because it's a string
    
    //Case 1: 
    alert(show);  //output "Color Picker"
    
    //Case 2: 
    alert(popup.show());  //output "Color Picker"
    
    //Case 3: 
    alert(showFn());  // output "Color Picker"
    

    (JS Bin)

    【讨论】:

      【解决方案4】:

      那是因为您将变量 show 视为一个函数。让我们简化一下:

      function a(){
       return "textA";
      }
      
      var obj={
        b: function(){ return "text b";}
      };
      
      console.log(a); // will output the function object
      console.log(a()); // will call a then output the result of the function --> "textA"
      console.log(obj.b); //will output the function object same as console.log(a)
      console.log(obj.b()); // will call b then output the result of the function --> "text b" 
      

      现在想象一下,我会做类似于您的第三个示例的操作:

      var anotherObj = a();
      console.log(anotherObj()); // you try to treat the return of a() as a function. will not work --> "string is not a function "
      

      例如,您可以这样做:

      console.log(window[anotherObj]());
      

      这将调用名为“textA”的函数。 Full Fiddle here

      关于作用域,this默认指的是window。在对象内部运行时,this 将引用此对象unless the function is applied to something else.

      【讨论】:

        【解决方案5】:

        this 始终引用当前对象或上下文。
        在情况 2 中,该对象是弹出窗口。这就是为什么您会在警报中看到 popup.title。

        当您将popup.show 分配给show 时,您在案例3 中有效地做的是在window 对象上创建一个句柄以显示(或至少是当前范围)。所以对于那个句柄,对象是window。 所以现在如果你调用这个句柄,它会显示你也在window对象上注册的title

        您可以通过调用设置上下文和/或像这样应用:

        var show=popup.show 
        alert(show.call(popup));
        

        【讨论】:

          猜你喜欢
          • 2015-08-17
          • 2011-06-08
          • 1970-01-01
          • 1970-01-01
          • 2018-10-17
          • 2022-08-11
          • 2012-11-08
          • 2011-01-11
          • 1970-01-01
          相关资源
          最近更新 更多