【前端學習筆記】call、apply、bind方法

來源:互聯網
上載者:User

標籤: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方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.