“这个”的范围 [英] The scope of "this"

查看:80
本文介绍了“这个”的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple object and I don't understand the concept(scope) of this by calling the functions of this object.

为什么在最后一个变种(3)中调用 show()(使用函数 show()没有父对象的内部对象)结果是这是全局的而不是内部变量 title(颜色选择器)

Why in the last variant (3) calling show() (with the function show() inside object without parent) the result is "This is global" and not the inside variable title("Color Picker")?

在含有变量 show 已定义,指的是全局对象。这是逻辑解释吗?

I have the vague idea that calling the function popup.show() after the gloabal variable show is defined, this refers to the global object. Is this the logic explanation?

代码: 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"


推荐答案

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

What this is depends on how you call the function in which you use this.

functionName();

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

In this case this will always refer to the global object (most often the window object).

示例

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点),这个仍然引用全局对象。

  • The example is a little bit constructed, but note, that the function func is called by simply write func();. So even if your function is places inside a constructor function (XY) and called from a function that is called as a method (see point 3), this still refers to the global object.
var obj = new functionName();

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

In this case this will refer to the new created object.

示例

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

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



3。作为方法调用



3. call as a method

obj.functionName();

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

In this case this will refer to the object that contains the function you are calling.

示例

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



4。使用调用



4. call by using apply

functionName.apply(thisObj, argArray);

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

In this case this will be new Object(thisObj), with thisObj being the first argument of the function apply.

示例

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所建议的,事件还会更改的上下文

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

Events are kind of a separate topic. They are not part of EcmaScript and are generally handled by different browsers differently. Nevertheless, the differences concerning this are minor and for IE > 8 as far as I know nonexistent.

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

this will refer to the DOM element that fired the event, except when you use inline event handler. In that case this will refer to the global object.

示例

<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 ,直接在HTML标记内部,将引用表示该标记的DOM元素。因此< button id =1onclick =clickit(this)>点击我< / button> 会将DOM元素传递给 clickit 事件处理程序。

  • Internet Explorer prior to version 9 didn't support addEventListener but attachEvent. Using this function will also result in this refering to the global object.
  • this, directly inside the HTML tag, will refer to the DOM element representing that tag. Therefore <button id="1" onclick="clickit(this)">click me</button> will pass the DOM element to the clickit event handler.

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

In your first two cases, you are calling your function as a method and in the last case, you are calling it as a function. That is why in the last case, this refers to the global object.

EDIT

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

I recently saw a very similar answer to a very similar question here on StackOverflow. Unfortunately I couldn't find it anymore, so I decided to post an answer by myself. But if someone knows what answer I mean, just leave a comment and I'll be happy to put a link to the original answer in my answer.

这篇关于“这个”的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆