•每一個函數都包含兩個非繼承而來的方法:call、apply。這倆個方法的用途都是在特定的作用域中調用函數,實際上等 於設置函數體內this對象的值。
•call、apply的用途之一就是傳遞參數,但事實上,它們真正強大的地方式能夠擴充函數賴以運行的作用域。
•使用call()、aplly()來擴充作用域的最大好處就是對象不需要與方法有任何耦合關係。
//call apply簡單的用法,綁定一些函數,用於傳遞參數 調用
function test(a,b){
return a + b;
}
function testcall(num1,num2){
//將test函數綁定到當前的函數上,我要使用test方法
return test.call(this,10,20);
}
function testapply(num1,num2){
return test.apply(this,[num1,num2]);
}
console.log(testapply(10,20));
//擴充作用域
window.color = 'red';
var obj = {color:'blue'};
var obj2 = {color : 'yellow'};
function showColor(){
console.log(this.color);
}
//使作用域不斷的變化,根據你傳遞的參數不同,綁定的作用域也不同
showColor.call(this); //red
showColor.call(obj); //blue
//call方法的簡單模擬與實現
function test(a,b){
return a + b;
}
//首字母大寫是約定俗成的方式定義對象
function Obj(x,y){
//內部定義一個x。y
this.x = x;
this.y = y;
return x * y;
}
var o = new Obj(10,20);
//內部一個簡單的實現
o.method = test;
console.log(o.method(o.x,o.y));
delete o.method;
console.log(test.call(o,o.x,o.y));