首页 > 代码库 > javascript中的this用法
javascript中的this用法
this这个关键字在javascript中很常见,也很重要。那么this到底是指什么呢?
总结:
1.this代表函数运行时自动生成的一个内部对象,只能在函数内部使用;
2.this始终指向调用函数的那个对象;
下面分四种情况,详细讨论this的用法
一:纯粹的函数调用
这是函数的最常用法,属于全局性调用,这里this就代表全局对象window
function test(){ this.x = 1; alert(this.x); console.log(this);//Window } test();
而下边这个案例:
var x = 2; function test(){ this.x = 1; alert(this.x); console.log(this);//Window } test(); console.log(x);//1
就可以证明这里函数中的this指的是window.
二:作为对象方法的调用
函数还可以作为某个对象的方法调用,这时this就指这个上级对象.
function test(){ console.log(this.x);//1 console.log(this);//o } var o = {}; o.x = 1; o.m = test; o.m();
三:作为构造函数调用
所谓构造函数,就是通过这个函数生成一个新的对象。这时,this就指向这个新对象
function Test(name){ this.name = name; console.log(this);//Test {name: "hehe"} } var t = new Test("hehe");
四:apply调用
apply()是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就是改变后的调用这个函数的对象。
this这里值得就是第一个参数的值,若参数为空,则默认值为全局对象
var x = 0; function test () { console.log(this); console.log(this.x); } var o = {}; o.x = 2; o.m = test; o.m();//this.x-->2 o.m.apply();//this.x-->0 // 结果: // Object {x: 2} // 2 // Window {…} // 0
javascript中的this用法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。