核心提示:this对象是在运行时候基于函数的执行环境绑定的。在全局函数中,this等于window,而当函数被作为某个对象的方法调用时,this等于那个对象。也就是说this关键字总是指代调用者,谁调用指向谁v...
this对象——是在运行时候基于函数的执行环境绑定的。在全局函数中,this等于window,而当函数被作为某个对象的方法调用时,this等于那个对象。
也就是说this关键字总是指代调用者,谁调用指向谁
var k = 10; function test(){ this.k = 20; } test(); //==window.test(); alert(test.k); //undefined alert(k); //20 //==alert(window.k);
*********************call和apply*************************
每一个函数都包含两个非继承而来的方法:call、apply。用途都是在指定的作用域中调用函数,实际上等于设置函数体内this对象的值。
//call apply 绑定一些函数,用于传递参数 function sum(x,y){ return x+y; } function call1(num1,num2){ //将一个函数sum绑定到当前函数call1内,传递sum需要的参数 return sum.call(this,num1,num2); } function apply1(num1,num2){ //将一个函数sum绑定到当前函数call1内,传递sum需要的参数 return sum.apply(this,[num1,num2]) } alert(call1(10,20)); //30 alert(apply1(20,40)); //60
call、apply真正强大的地方是能够扩充函数赖以运行的作用域。而对象不需要与方法有任何耦合关系。
window.color = "red"; var obj = {"color":"blue"}; function showColor(){ alert(this.color); } showColor.call(this); //this指window showColor.call(obj); //this指obj
call方法简单模拟与实现
//function方法 function test1(a,b){ return a+b; } //自定义对象 function Obj(x,y){ this.x = x; this.y = y; return x*y; } var o = new Obj(10,20); o.method = test1; alert(o.method(o.x,o.y)); delete o.method; //alert(test1.call(o,o.x,o.y));