js的apply和call

來源:互聯網
上載者:User

標籤:繼承   職業   nts   width   應用   name   ack   方法   數組   

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script>        //第一個用途:函數上下文模式改變this的指向        var age=19;        function fun() {            console.log(this.age);        }        var obj={            age:26        };        fun.apply(obj);        fun.call(obj)        //總結:apply和call,第一個參數功能都是一樣,都是可以改變this指向為第一個參數對象。        //當傳遞對象為null的時候,為window調用        //應用1:將參數用“-”拼接        function fun2() {            //arguments是一個偽裝數組,不能調用join方法,通過apply轉換替代對象來調用            console.log(Array.prototype.join.apply(arguments, ["-"]));            console.log(Array.prototype.join.call(arguments, "-"));        }        fun2(1,2,3,4);        //應用4:借用建構函式實現繼承        function Persion() {            this.name="張三";            this.age=18;        }        function Student() {            Persion.apply(this);        }        var stu=new Student();        console.log(stu);        //第二個用途:第二個到第N個參數的處理        function fun1(name,work) {            console.log("名字為"+name+";年齡為"+this.age+"職業"+work);        }        var obj1={            age:30        };        /*        * apply和call第二個參數都是函數的參數        * apply是傳遞的數組,執行的時候是將數組遍曆然後作為參數傳遞。        * call傳遞的是分開的參數        * */        fun1.apply(obj1,["張三","金融"]);        fun1.call(obj1,"張三","金融");        //應用2:apply的遍曆        window.onload=function () {            var divs=document.querySelectorAll("div");            var spans=document.querySelectorAll("span");            var arr=[];            arr.push.apply(arr,divs);            arr.push.apply(arr,spans);            for(var i=0;i<arr.length;i++){                arr[i].style.backgroundColor="red";            }        }        //應用3:求最大值        var arr1=[3,6,1,78,23];        console.log(Math.max.apply(null, arr1));    </script>    <style>        div,span{            display: inline-block;            width: 50px;            height: 50px;            border: 1px solid pink;        }    </style></head><body><div></div><div></div><div></div><div></div><br><span></span><span></span><span></span><span></span></body></html>

 

js的apply和call

相關文章

聯繫我們

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