js中function是有上下文的,如果不注意的话很容易出错的,如下:
var fun1=function(){
this.name="in the function";
this.say=function(){
alert(this.name);
};
};
name="out the function";
var obj = new fun1();
var list = [];
list.push(obj.say);
obj.say.call();//out the function
obj.say();//in the function
list[0]();//undefined
在上面这块代码中,
第一次call因为没有指定上下文,所以在最外层运行函数,this指向window
第二次因为直接运行,this指向.say()前面的对象
第三次比较特殊,我们把function放在一个list中,再去执行,这时候this指向了这个数组list