call和apply方法

來源:互聯網
上載者:User

標籤:nal   height   apply()   www   1.0   public   ansi   xhtml 1.0   控制   

普通函數中是否也有this關鍵字,this指向誰呢?

<script type="text/javascript">     function myfun(){        console.log(this);     }     myfun();</script>

控制函數內部的this指向:

函數都可以打點調用call()和apply()方法,可以幫我們制定函數內部的this指向,在函數調用過程使用這兩個方法。

 

var oDiv = document.getElementsByTagName(‘div‘);function fun(){   console.log(this);}//fun.call(oDiv);fun.apply(oDiv);

 

作用:

 1、執行fun函數

2、在fun函數內部指定this的指向oDiv

 

<!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>Document</title>
<style type="text/css">
div{
width: 200px;
height: 200px;
background: red;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
<script type="text/javascript">
/*function fun(){
console.log(this);
}
fun();*/
var oDiv = document.getElementsByTagName(‘div‘)[0];
/* function fun(){
console.log(this);
}
//fun.call(oDiv);
fun.apply(oDiv);*/

/*function sum(a,b){
this.style.backgroundColor = "pink";
}
sum.call(oDiv);
sum.apply(oDiv);*/

function sum(a,b){
this.style.backgroundColor = "pink";
console.log(a+b);
}
sum.call(oDiv,2,3);
sum.apply(oDiv,[3,5]);
</script>

 

call和apply 區別:

函數傳遞參數的文法不同。

sum.call(oDiv,參數1,參數2,參數3...);sum.apply(oDiv,[參數1,參數2,參數3...])

 

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.