Usage of this in JavaScript: 1. Use this to refer to the global object; 2. Use this to refer to the superior object; 3. Use this to refer to the new object; 4. Use this to refer to the first parameter. .
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
Usage of this in JavaScript:
1. Use this in general function methods to refer to the global object
function test(){ this.x = 1; alert(this.x); } test(); // 1
2. When called as an object method, this refers to the superior object
function test(){ alert(this.x); } var o = {}; o.x = 1; o.m = test; o.m(); // 1
3. As a constructor call, this refers to the object created by new
function test(){ this.x = 1; } var o = new test(); alert(o.x); // 1 //运行结果为1。为了表明这时this不是全局对象,我对代码做一些改变: var x = 2; function test(){ this.x = 1; } var o = new test(); alert(x); //2
4. Apply call, the apply method is used to change the function The calling object. The first parameter of this method is the object that calls this function after the change. This refers to the first parameter
var x = 0; function test(){ alert(this.x); } var o={}; o.x = 1; o.m = test; o.m.apply(); //0 //apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。如果把最后一行代码修改为 o.m.apply(o); //1
Related free learning recommendations: javascript( video)
The above is the detailed content of What are the usages of this in javascript?. For more information, please follow other related articles on the PHP Chinese website!