this关键字
this是javaScript语言的一个关键字。它代表函数运行时自动生成一个内部对象,只能在函数内部使用。
1、在函数中使用this
在函数中使用this属于全局使用,代表全局对象,通过window对象来访问。
<script type="text/javascript">
function test(){
this.x=1;
console.log(this);
}
test();//调用者是window
console.log(x);//相当于定义在全局对象上的属性。
console.log(this.x);
</script>
2、在对象中使用this
在对象中使用this,表示当前的上级对象。
<script type="text/javascript">
var obj(){
name:"zhangsan",
age:20,
sayHello:function(){
console.log(this.name),//这里的this表示obj对象
console.log(this),
},
}
obj.sayHello();
</script>