冒充方法call和apply 簡述

來源:互聯網
上載者:User

標籤:javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

<title>call</title>

<script type="text/javascript">


// 入門

function sub(x,y){

return x-y;

}


function plus(x,y){

return x+y;

}


alert(plus(2,1));//正常執行相加

alert(sub.apply(plus,[2,1]));//使用apply方法,讓plus冒充sub,執行相減(這裡的[]一定要加)


// 進階

function sub(x,y){

return x-y;

}

function plus(x,y){

return sub.apply(this,[x, y]);//直接將冒充方法寫在函數體內,減少冗餘

}

alert(plus(2,1));//執行相減


//再次進階

function sub(x,y){

return x-y;

}

function plus(x,y){

return sub.apply(this,arguments);//用內建的arguments變數自動尋找所有參數

}

function plusForCall(x,y){

return sub.call(this,x,y);//使用call方法,讓plusForCall冒充sub,執行相減(這裡的[]一定不能加),

//這就是call和apply的區別

}

function plusForCallByArgument(x,y){

return sub.call(this,arguments);//***這個方法是錯誤的call方法內不能使用arguments變數

}

//綜上所述,當我們使用冒充方法的時候,有參數的時候使用apply,無參數的時候使用call


//用冒充方法擴大範圍

var color="blue";

var goods={

color:"red"

};

function getColor(){

alert(this.color);

}

getColor();//直接使用是blue,因為this在全域環境中,就代表window

getColor.call(goods);//冒充goods,這時的this代表goods

</script>

</head>

<body>

</body>

</html>


本文出自 “一隻WEB菜鳥的自白” 部落格,請務必保留此出處http://6852489.blog.51cto.com/6842489/1570917

冒充方法call和apply 簡述

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.