欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS函數(shù)的call和apply的實現(xiàn)方法區(qū)別分析

 更新時間:2023年10月15日 15:23:44   作者:陽哥  
這篇文章主要為大家介紹了JS函數(shù)的call和apply的實現(xiàn)方法區(qū)別分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

 方法示例

//apply用法
        function A(alpha,age){
            this.name = 'bob';
            alert(alpha + arguments[1] + this.name)
        }
        (function(){
            A.apply(this,['a',25])
        })()
        
        //call方法
        function B(alpha){
            this.name = 'alice';
            alert(alpha + this.name)
        }
        
        (function(){
            B.call(this,'b')
        })()
        
        //普通函數(shù)
        function love(alpha){
            this.name = 'alice';
            alert(alpha + this.name)
        }
        
        (function(){
            love.call(this,'love')
        })()
        //async函數(shù)
        async function create(alpha){
            this.name = 'op';
            var res = await compute();
            alert(alpha + this.name + res)
        }
        (function(){
            create.call(this,'b')
        })()
        //generator函數(shù)
        function * gen(num){
            console.log(num);
            num ++;
            yield 'first'
            yield 'then'
            yield 'final'
            return num
        }
        (function(){
            gen.call(this,0)
        })()
        
        let it = gen(3);

          console.log(it.next())  // {value: "first", done: false}
          console.log(it.next())   // {value: "then", done: false}
          console.log(it.next())   // {value: "final", done: false}
          console.log(it.next())   // {value: "4", done: true}
          
          
          function compute(){ 
              var num = 0;
              for(let i = 0; i < 10 ; i++){//1+2+3+4+5+ ... + 9 =>(1+9)*9/2 = 45
                  num += i;
              }
              return num
          }

apply和call方法的相同點

可以使得宿主(當前函數(shù)對象)在其自己作用域進行執(zhí)行,比如在第一個實例中,使用call和apply的第一個參數(shù)context(上下文),也可稱為this對象,傳遞給構(gòu)造函數(shù)A,此時this的作用域為當前構(gòu)造函數(shù)A下。

不同點

傳遞的參數(shù)不同,call第二個參數(shù)傳遞的可以是任何數(shù)據(jù)類型 函數(shù)、數(shù)組...,而apply傳遞的是必須是數(shù)組或者類數(shù)組。

兩個方法該如何選擇?

根據(jù)你要傳入的參數(shù)來做選擇,不需要傳參或者只有1個參數(shù)的時候,用call,當要傳入多個對象時,用apply

以上就是JS函數(shù)的call和apply的實現(xiàn)方法區(qū)別分析的詳細內(nèi)容,更多關(guān)于JS函數(shù)call apply方法的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論