JavaScript中this关键字指代总结

时间:2021-11-21 19:51:59

JavaScript中this关键字指代总结

在JavaScript中,this代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。
总的原则:this指的是调用函数的那个对象

1. 纯粹的函数调用

/*情况一:纯粹的函数调用*/
/*this代表全局对象*/
var x = 1;
var y = 2;

function test1(){
this.y = 20;
console.log(this.x);
console.log(this); //Window
}

test1(); //1
console.log(y); //20

2. 作为对象的方法调用

/*情况二:作为对象方法的调用*/
/*this代表上下文*/
var o = {};
o.x = 3;
o.m = test2;
o.m(); //3

function test2(){
console.log(this.x);
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<p id="txt"></p>
<button id="btn">Testbtn</button>
<script type="text/javascript">
/*addEventListener()的作用域为元素作用域*/
/*this代表DOM元素*/
document.getElementById("btn").addEventListener("click", function(){
document.getElementById("txt").innerHTML = "Hello World-addEventListener";
console.log(this.id); //btn
});
</script>
</body>
</html>

3. 作为构造函数

/*情况三:作为构造函数*/
/*this代表通过构造函数生成的新对象*/
function test3(){
this.x = 5;
}

var o2 = new test3();
console.log(o2.x); //5

4. apply/call调用

/*情况四:apply/call调用*/
/*this代表改变后调用这个函数的对象*/
var X = 100;

function test4(a,b,c){
console.log(this.X + "-" +String(a) + "-" + String(b) + "-" + String(c));
}

var o3 = {};
o3.X = 7;
var o4 = {};
o4.X = 9;
o3.m = test4;

o3.m.apply();//参数为空时,默认调用全局对象:100-undefined-undefined-undefined
o3.m.apply(o3); //7-undefined-undefined-undefined
o3.m.call(); //100-undefined-undefined-undefined
o3.m.apply(o4,[1,2,3]); //9-1-2-3
o3.m.call(o4,1,3,4,5); //9-1-3-4
o3.m.apply(o4,[1,2]); //9-1-2-undefined