this指针:
1、以下代码的this就是window
<script type="text/javascript"> this.a = "aaa"; console.log(a);//aaa console.log(this.a);//aaa console.log(window.a);//aaa console.log(this);// window console.log(window);// window console.log(this == window);// true console.log(this === window);// true </script>
2、运行结果我们发现ftn04虽然在ftn03作用域下,但是执行它里面的this指针也是指向window
|
<script type="text/javascript"> function ftn03(){ var ftn04 = function(){ console.log(this);// window }; ftn04(); } ftn03(); </script>
----------------------------------------------------------------------------这下子坏了,this都指向window,那我们到底怎么才能改变它了?
1、new
2、call()
3、apply()
----------------------------------------------------------------------------call和apply方法的作用相同,就是参数不同,call和apply的第一个参数都是一样的,但是后面参数不同,apply第二个参数是个数组,call从第二个参数开始后面有许多参数。
Call和apply是将this指针指向方法的第一个参数。
例子1、:
name="david beckham"; function show(){ console.log(name); console.log(this.name); } show(); var obj={ name:"tombflylee" } show.call(obj);
结果:
david beckham david beckham david beckham tombflylee
例子2、
name="david beckham"; function show(index){ console.log(name); console.log(this.name); console.log(index); } show(); var obj={ name:"tombflylee" } show.call(obj,"xingliying");结果:
david beckham david beckham undefined david beckham tombflylee xingliying