標籤:text rgs test 函數 java 方法 prot cal 上下文
1.call()方法:
// move函數實現移動平面圖上一個點位置功能var move = function(x,y){ this.x += x; this.y += y;}// 定一個點pvar p = {x:1, y:1}; // 調用call 方法,此時p點直接會移動。move.call(p,1,2); console.log(p); // --> {x:2,y:3}
2.apply()方法:
// move函數實現移動平面圖上一個點位置功能var move = function(x,y){ this.x += x; this.y += y;}// 定一個點pvar p = {x:1, y:1}; // 調用apply方法,此時p點直接會移動。move.apply(p,[1,2]); console.log(p); // --> {x:2,y:3}
3.bind()方法:
/** 函數作為傳回值--bind **/// move函數實現移動平面圖上一個點位置功能var move = function(x,y){ this.x += x; this.y += y;}// // // 定一個點pvar p = {x:1, y:1}; // // bind方法收受一個參數,並返回一個接受餘下參數的函數過程。此時p點並沒有移動。var pmove0 = move.bind(p); console.log(p); // --> {x:1,y:1}// // 這時p移動到了(2,3)位置。pmove0(1,2); console.log(p); // --> --> {x:2,y:3}
// 當然你也可以這樣調用var pmove1 = move.bind(p,1);console.log(p);pmove1(2);console.log(p);
// 或者這樣調用var pmove2 = move.bind(p,1,2);console.log(p);pmove2();console.log(p);
//bind()相容寫法if (!Function.prototype.bind) { //如果原型上沒有bind方法 Function.prototype.bind = function (context) { var args = arguments, //擷取要傳入的所有參數 obj = arguments[0], //擷取要綁定的上下文 func = this; //擷取要調用的函數 return function(){ //返回一個新的函數 var argc = Array.prototype.slice.call(args,1); //擷取bind的剩餘傳入參數 Array.prototype.push.apply(argc,arguments); //將調用時的參數放到最後 return func.apply(obj,argc); //使用新的this執行func函數 } }}
4.call()、apply()方法改變this指向
//例子調用apply()方法,call()方法相同function test(){console.log(‘I am test‘);}var obj ={move:function(x,y){console.log(x);console.log(y);console.log(this); // --> obj{move:function(){}}}}obj.move(44,55);// 調用apply方法obj.move.apply(test,[66,88]); // --> function test(){ console.log(‘I am test‘) ;}
5.bind()方法改變this指向
//調用bind()方法function test(){console.log(‘I am test‘);}var obj ={move:function(x,y){console.log(x);console.log(y);console.log(this); }}obj.move(44,55);// this --> obj{move:function(){}}var testMove = obj.move.bind(test); testMove(66,88); // this --> function test(){ console.log(‘I am test‘); };
【前端學習筆記】call、apply、bind方法