JS中的call、apply、bind方法

來源:互聯網
上載者:User

標籤:

JS中的call、apply、bind方法一、call()和apply()方法

1.方法定義

call方法:

文法:call([thisObj[,arg1[, arg2[,   [,.argN]]]]])

定義:調用一個對象的一個方法,以另一個對象替換當前對象。

說明:

call 方法可以用來代替另一個對象調用一個方法。call 方法可將一個函數的物件內容從初始的上下文改變為由 thisObj 指定的新對象。

如果沒有提供 thisObj 參數,那麼 Global 對象被用作 thisObj。

apply方法:

文法:apply([thisObj[,argArray]])

定義:應用某一對象的一個方法,用另一個對象替換當前對象。

說明:

如果 argArray 不是一個有效數組或者不是 arguments 對象,那麼將導致一個 TypeError。

如果沒有提供 argArray 和 thisObj 任何一個參數,那麼 Global 對象將被用作 thisObj, 並且無法被傳遞任何參數。

2、常用執行個體

a、

function add(a,b)  {    alert(a+b);  }  function sub(a,b)  {    alert(a-b);  }  add.call(sub,3,1);

這個例子中的意思就是用 add 來替換 sub,add.call(sub,3,1) == add(3,1) ,所以運行結果為:alert(4); // 注意:js 中的函數其實是對象,函數名是對 Function 對象的引用。

b、

function Animal(){  this.name = "Animal";  this.showName = function(){    alert(this.name);  }}function Cat(){  this.name = "Cat";}var animal = new Animal();var cat = new Cat();

通過call或apply方法,將原本屬於Animal對象的showName()方法交給對象cat來使用了。

//輸入結果為"Cat"   

animal.showName.call(cat,",");   

//animal.showName.apply(cat,[]); 

call 的意思是把 animal 的方法放到cat上執行,原來cat是沒有showName() 方法,現在是把animal 的showName()方法放到 cat上來執行,所以this.name 應該是 Cat。

c、實現繼承

function Animal(name){    this.name = name;    this.showName = function(){      alert(this.name);    }  }  function Cat(name){  Animal.call(this, name);}  var cat = new Cat("Black Cat"); cat.showName();

Animal.call(this) 的意思就是使用 Animal對象代替this對象,那麼 Cat中不就有Animal的所有屬性和方法了嗎,Cat對象就能夠直接調用Animal的方法以及屬性了.

d、多重繼承

function Class10()  {    this.showSub = function(a,b)    {      alert(a-b);    }  }  function Class11()  {    this.showAdd = function(a,b)    {      alert(a+b);    }  }  function Class2()  {    Class10.call(this);    Class11.call(this);  }

很簡單,使用兩個 call 就實現多重繼承了當然,js的繼承還有其他方法,例如使用原型鏈,這個不屬於本文的範疇,只是在此說明call 的用法。說了call ,當然還有 apply,這兩個方法基本上是一個意思,區別在於 call 的第二個參數可以是任意類型,而apply的第二個參數必須是數組,也可以是arguments。代碼如下:

var func=new function(){this.a="func"} var myfunc=function(x,y){ var a="myfunc"; alert(this.a); alert(x + y); } myfunc.call(func,"var"," fun");// "func" "var fun" myfunc.apply(func,["var"," fun"]);// "func" "var fun"
二、bind

在EcmaScript5中擴充了叫bind的方法(IE6,7,8不支援),使用方法如下

function T(c) {  this.id = "Object";  this.dom = document.getElementById("scroll");}T.prototype = {  init: function() {     //①    this.dom.onmouseover = function() {      console.log("Over-->"+this.id);    }     //②    this.dom.onmouseout = function() {      console.log("Out -->"+this.id);    } .bind(this)  }};(new T()).init();

結果:

通過①和②的對照加上顯示的結果就會看出bind的作用:改變了內容相關的this

bind與call很相似,,例如,可接受的參數都分為兩部分,且第一個參數都是作為執行時函數上下文中的this的對象。

不同點有兩個:

①bind的傳回值是函數

//都是將obj作為內容相關的this

function func(name,id) {    console.log(name,id,this);}var obj = "Look here";

//什麼也不加func("    ","-->");

//使用bind是 返回改變上下文this後的函數

var a = func.bind(obj, "bind", "-->");

a();

//使用call是 改變上下文this並執行函數

var b = func.call(obj, "call", "-->");

結果:

②後面的參數的使用也有區別

function f(a,b,c){    console.log(a,b,c);}var f_Extend = f.bind(null,"extend_A")

f("A","B","C")  //這裡會輸出--> A B C

f_Extend("A","B","C")  //這裡會輸出--> extend_A A B

f_Extend("B","C")  //這裡會輸出--> extend_A B C

f.call(null,"extend_A") //這裡會輸出--> extend_A undefined undefined

call 是 把第二個及以後的參數作為f方法的實參傳進去

而bind 雖說也是擷取第二個及以後的參數用於之後方法的執行,但是f_Extend中傳入的實參則是在bind中傳入參數的基礎上往後排的。

//這句代碼相當於以下的操作

var f_Extend = f.bind(null,"extend_A")

//↓↓↓

var f_Extend = function(b,c){    return f.call(null,"extend_A",b,c);}

舉一個應用情境:例如現在有一個方法 根據不同的檔案類型進行相應的處理,通過bind 就可以建立出簡化版的處理方法

function FileDealFunc(type,url,callback){  if(type=="txt"){...}  else if(type=="xml"){...}  .....}var TxtDealFunc = FileDealFunc.bind(this,"txt");

//這樣使用的時候更方便一些

FileDealFunc("txt",XXURL,func);  //原來

TxtDealFunc(XXURL,func); //現在

以下是相容處理

if (!Function.prototype.bind) {    Function.prototype.bind = function(obj) {        var _self = this            ,args = arguments;        return function() {            _self.apply(obj, Array.prototype.slice.call(args, 1));        }    }}

-------------------------------------------------------------------------------------------------------------------------------------

完轉載需註明轉載字樣,標註原作者和原博文地址。

更多閱讀:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

http://www.jb51.net/article/61053.htm

http://www.zhangxinxu.com/wordpress/2012/10/ecmascript-es5-bind-array-slice-call-apply/

JS中的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.