javascript中this详解

作者:暴躁小n | 创建时间: 2023-05-15
javascript中this详解

this

this是javascript的一个关键字,随着函数使用场合不同,this的值会发生变化。但是总有一个原则,那就是this指的是调用函数的那个对象。

纯粹函数调用

function test(){ this.x = 1; alert(x); } test();  //输出 1 //这里的this就是全局变量。this.x就自当于增加一个全局变量x var x = 1; function test() { alert(this.x);  //调用全局变量x } test();//1 var x = 1; function test() { this.x = 0; //给全局变量x赋值 } test(); alert(x); //0 以上几个例子都能很好的说明在函数中 this 就是全局对象Global

作为方法调用

function test() { alert(this.x); } var o = {}; o.x = 1; o.m = test; o.m(); //1 //当作为方法调用时,那么this就是指这个上级对象

作为构造函数调用

function test() { this.x = 1; } var o = new test(); alert(o.x);//1 //这时,这个this就是指这个对象o

apply与call调用

var x = 0; function test() { alert(this.x); } var o = {}; o.x = 1; o.m = test; o.m.apply(); //0 o.m.apply(o);  //1 o.m.call(o); //this指向的是apply/call中的第一个参数

点击展开全文

更多推荐