Home > Web Front-end > Front-end Q&A > What does this mean in javascript

What does this mean in javascript

青灯夜游
Release: 2021-10-20 13:55:08
Original
9959 people have browsed it

In js, this means "this; current" and is a pointer variable that dynamically 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 always points to the real caller of the function in which it is located; if there is no caller, it points to the global object window.

What does this mean in javascript

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

After a JavaScript function is called, it will be executed in a specific running environment. This running environment is the caller of the function, or the object of the calling function. If the function has no caller (not through the object, but directly), then the running environment is the global object window.

In order to be able to reference (access) the running environment during function execution, JavaScript specifically adds a this keyword. 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 point 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.

In the section "JS this and calling objects", we have talked about the preliminary use of this pointer. Readers who do not understand it can click on the link to learn. This section focuses on an in-depth analysis of this pointer.

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[.属性]
Copy after login

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对象
Copy after login

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
Copy after login

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
}
Copy after login

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
Copy after login

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;  //实例化
Copy after login

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指向数值对象
Copy after login

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>
Copy after login

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);
}
Copy after login

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);
}
Copy after login

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);
Copy after login

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);
Copy after login

[Recommended learning: javascript advanced 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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template