Home  >  Article  >  Web Front-end  >  What does this mean in javascript

What does this mean in javascript

青灯夜游
青灯夜游Original
2021-06-30 14:38:166704browse

The Chinese meaning of this is "current; this". It is a pointer variable in JavaScript, which points to the running environment of the current function. When the same function is called in different scenarios, the pointer of this will change, but it will always point to the real caller of the function in which it is located; if there is no caller, this will point to the window.

What does this mean in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript The scope of a function is static, but the function call is dynamic. Since functions can be executed in different running environments, JavaScript defines the this keyword in the function body to obtain the current running environment.

this is a pointer variable that points to the running environment of the current function.

When the same function is called in different scenarios, the pointer of this may also change, but it will always point to the real caller of the function in which it is located (whoever calls it points to who); if there is no caller, this Just point to the global object window.

Use this

This is automatically generated by the JavaScript engine when executing the function. It is a dynamic pointer that exists within the function and refers to the current calling object. The specific usage is as follows:

this[.属性]

If this does not contain attributes, the current object is passed.

This is flexible in usage and the values ​​it contains are also varied. For example, the following example uses the call() method to continuously change the object this refers to within a function.

var x = "window";  //定义全局变量x,初始化字符串为“window”
function a () {  //定义构造函数a
    this.x = "a";  //定义私有属性x,初始化字符a
}
function b () {  //定义构造函数b
    this.x = "b";  //定义私有属性x,初始化为字符b
}
function c () {  //定义普通函数,提示变量x的值
    console.log(x);
}
function f () {  //定义普通函数,提示this包含的x的值
    console.log(this.x);
}
f();  //返回字符串“window”,this指向window对象
f.call(window);  //返回字符串“window”,指向window对象
f.call(new a());  //返回字符a,this指向函数a的实例
f.call(new b());  //返回字符b,this指向函数b的实例
f.call(c);  //返回undefined,this指向函数c对象

The following is a brief summary of the performance and response strategies of this in 5 common scenarios.

1. Ordinary calls

The following example demonstrates the impact of function references and function calls on this.

var obj = {  //父对象
    name : "父对象obj",
    func : function () {
        return this;
    }
}
obj.sub_obj = {  //子对象
    name : "子对象sub_obj",
    func : obj.func
}
var who = obj.sub_obj.func();
console.log(who.name);  //返回“子对象sub_obj”,说明this代表sub_obj

If you change the func of the sub-object sub_obj to a function call.

obj.sub_obj = {
    name : "子对象sub_obj",
    func : obj.func()  //调用父对象obj的方法func
}

Then this in the function represents the parent object obj where the function is defined.

var who = obj.sub_obj.func;
console.log(who.name);  //返回“父对象obj”,说明this代表父对象obj

2. Instantiation

When calling a function using the new command, this always refers to the instance object.

var obj = {};
obj.func = function () {
    if (this == obj) console.log("this = obj");
    else if (this == window) console.log("this = window");
    else if (this.contructor == arguments.callee) console.log("this = 实例对象");
}
new obj.func;  //实例化

3. Dynamic calling

Use call and apply to force this to point to the parameter object.

function func () {
    //如果this的构造函数等于当前函数,则表示this为实例对象
    if (this.contructor == arguments.callee) console.log("this = 实例对象");
    //如果this等于window,则表示this为window对象
    else if (this == window) console.log("this = window对象");
    //如果this为其他对象,则表示this为其他对象
    else console.log("this == 其他对象 \n this.constructor =" + this.constructor);
}
func();  //this指向window对象
new func();  //this指向实例对象
cunc.call(1);  //this指向数值对象

In the above example, when func() is called directly, this represents the window object. When a function is called using the new command, a new instance object will be created, and this will point to this newly created instance object.

When using the call() method to execute the function func(), since the parameter value of the call() method is the number 1, the JavaScript engine will force the number 1 to be encapsulated into a numerical object, and this will point to this Numeric object.

4. Event processing

In the summary of event processing functions, this always points to the object that triggered the event.

<input type="button" value="测试按钮" />
<script>
    var button = document.getElementsByTagName("put")[0];
    var obj = {};
    obj.func = function () {
        if (this == obj) console.log("this = obj");
        if (this == window) console.log("this = window");
        if (this == button) console.log("this = button");
    }
    button.onclick = obj.func;
</script>

In the above code, this contained in func() no longer points to the object obj, but to the button button, because func() is called after being passed to the button's event handling function. .

If you use the DOM2 level standard to register the event handler function, the procedure is as follows:

if (window.attachEvent) {  //兼容IE模型
    button.attachEvent("onclick", obj.func);
} else {  //兼容DOM标准模型
    button.addEventListener("click", obj.func, true);
}

In the IE browser, this points to the window object and button object, but in the DOM standard browser it only points to button object. Because, in the IE browser, attachEvent() is a method of the window object. When this method is called, this will point to the window object.

In order to solve browser compatibility issues, you can call the call() or apply() method to force the method func() to be executed on the object obj to avoid the problem of different browsers parsing this differently.

if (window.attachEvent) {
    button.attachEvent("onclick", function () {  //用闭包封装call()方法强制执行func()
        obj.func.call(obj);
    });
} else {
    button.attachEventListener("onclick", function () {
        obj.func.call(obj);
    }, true);
}

When executed again, this contained in func() always points to the object obj.

5. Timer

Use the timer to call the function.

var obj = {};
obj.func = function () {
    if (this == obj) console.log("this = obj");
    else if (this == window) console.log("this = window对象");
    else if (this.constructor == arguments.callee) console.log("this = 实例对象");
    else console.log("this == 其他对象 \n this.constructor =" + this.constructor);
}
setTimeOut(obj.func, 100);

In IE, this points to the window object and button object. The specific reason is the same as the attachEvent() method explained above. In DOM-compliant browsers, this points to the window object, not the button object.

Because the method setTimeOut() is executed in the global scope, this points to the window object. To resolve browser compatibility issues, you can use the call or apply methods.

setTimeOut (function () {
    obj.func.call(obj);
}, 100);

【Related recommendations: javascript learning tutorial

The above is the detailed content of What does this mean in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn