JavaScript中this
听燕十八老师的《JavaScript高级》课程,对JavaScript中this的笔记记录!
js中函数的四种调用方式:
1.作为普通的函数来调用时,this的值指向window;在ECMASCRIPT5标准中,如果this为null,则解释成undefined。
<script type="text/javascript">
console.log(window.xx);//undefined
function t(){
this.xx=33;
}
t();
console.log(window.xx);//33
</script>
2.作为对象的方法来调用,this指向方法的调用者即母体对象,不管被调用的函数声明时属于方法还是函数。
var obj={
xx:999,
t:function(){
console.log(this.xx)
}
}
obj.t();//999
var dog={
xx:"wangwang"
}
dog.t=obj.t;
dog.t();//wangwang
3.函数作为构造函数调用时,因为js中没有类的概念,创建对象是用构造函数来完成,或者直接用json格式来写对象
function Dog(name,age){
this.name=name;
this.age=age;
this.bark=function(){
console.log("my name is:"+this.name);
}
}
var dog=new Dog("虎子",2);
dog.bark(); //my name is:虎子
4.函数被call、apply调用,语法:
函数.call(对象,参数1,参数2......参数n)
function t(num){
console.log("我的真实年龄是:"+this.age);
console.log("但我一般告诉别人我:"+(this.age+num));
}
var man={name:"wangwu",age:28};
t.call(man,-10);
案例分析:
var name="this is the window!";
var obj={
name:"javascript",
t:function(){
console.log(this.name);
}
}
var dog={name:"huzi"}
var tem=obj.t;
tem();//相当于window.tem(),this指向window
dog.t=obj.t;
dog.t();//this指向dog
(dog.t=obj.t)()
//括号内是一个表达式,返回的是一个"值",即t函数
//强调是值说明不是通过引用来调用的,而是立即调用函数本身
//效果等同于(function(){console.log(this.name)})()
//此调用中this指向的是null,而null在这里被解释成了window
//此处调用与上面的tem()调用母体不同,有本质的区别
注:有this操作的函数(如this.age=22)不能直接调用而要用new来调用,根本原因是直接调用,this指向window,会污染全局变量!
浙公网安备 33010602011771号