this:this对象是指在运行时期基于运行环境所绑定的也就是说this老是指向调用者数组
代码说明:app
var k=10; function test(){ this.k=20; } test();//test()<===>window.test() alert(test.k);//undefined alert(k)//20 /*说明:this:this对象是指在运行时期基于运行环境所绑定的也就是说this老是指向调用者; 代码分析: 1.var k=10;至关于window.k=10; 2.test函数中的this指向的是全局做用域中的window对象,因此此时this.k等价于window.k, 因为this.k从新赋值了20,因此此时k就等于20, 而test.k因为是个函数的局部变量, 因此,test.k并无赋值,因此弹出undefined */
call,apply方法:函数
代码说明:this
//简单用法:绑定一些函数,用于传参调用; function add(x,y){ return x+y; } function call1(a,b){ //在test函数中调用add方法而且将test函数的参数传递给add方法 return add.call(this,a,b); } call1(1,2);//返回值为3 function apply1(c,d){ //apply方法和call方法运行效果是同样的,可是call传递普通参数,可是,apply传递是一个数组; return add.apply(this,[c,d]); } apply1(1,2);//返回值为3 //扩充函数做用域实例 window.color="red"; var obj={color:"green"}; function showColor(){ alert(this.color); } showColor.call(this);//red;this就是window; showColor.apply(obj);//green,由于绑定的是obj,所以改变了函数做用域