Javascript中this的指向

传入的参数是被new过的构造函数,那么this就是指向实例化的对象本身;

传入的参数是函数的别名,那么函数的this就是指向window

如果我们想把被传入的函数对象里this的指针指向外部字面量定义的对象,那么我们就是用apply和call

 1 var name = "I am window";
 2 var obj = {
 3     name:"sharpxiajun",
 4     job:"Software",
 5     ftn01:function(obj){
 6         obj.show();
 7     },
 8     ftn02:function(ftn){
 9         ftn();
10     },
11     ftn03:function(ftn){
12         ftn.call(this);
13     }
14 };
15 function Person(name){
16     this.name = name;
17     this.show = function(){
18         console.log("NAME:" + this.name);
19         console.log(this);
20     }
21 }
22 var p = new Person("Person");
23 obj.ftn01(p);//
24 obj.ftn02(function(){
25    console.log(this.name);
26    console.log(this);
27 });
28 obj.ftn03(function(){
29     console.log(this.name);
30     console.log(this);
31 });

 

posted @ 2015-09-02 10:13  张彦正  阅读(99)  评论(0编辑  收藏  举报