• call 和 apply 方法


    1:每个函数都包含两个非继承而来的方法:call(),apply().

    2:call方法和apply方法作用是一样的。

    下边是call的使用例子:

     1 window.color = 'red';
     2 document.color = 'yellow';
     3 var s1 = {color: 'blue'};
     4 
     5 function getColor (){
     6     console.log(this.color);
     7 }
     8 getColor.call(); //red (默认传递参数)
     9 getColor.call(window);// red
    10 getColor.call(document);//yellow
    11 getColor.call(s1);//blue
    12 getColor.call(this);//red
     1 var Pet={
     2   words : '...',
     3   speak : function(say){console.log(say+ ' ' + this.words);}    
     4 }
     5 
     6 Pet.speak('howling'); //howling...
     7 
     8 
     9 
    10 var Dog = {words: 'wang wang'}
    11 
    12 Pet.speak.call(Dog, 'barking');// barking wang wang

    下边是apply使用例子

     1 window.number = 'one';
     2 document.number = 'two';
     3 var s2 = {number: 'three'};
     4 
     5 function getNum(){ console.log(this.number); }
     6 
     7 getNum.apply(); // one 默认
     8 getNum.apply(window); //one
     9 getNum.apply(document);//two
    10 getNum.apply(s2);//three
    11 getNum.apply(this);//one
     1 function Pet(words){
     2   this.words = words;
     3   this.speak = function(){ console.log(this.words) }  
     4 }
     5 
     6 function Dog(words){
     7    // Pet.call(this, words); 
     8    Pet.apply(this, arguments);
     9 }
    10 
    11 var dog = new Dog('wang wang');
    12 dog.speak();// wang wang

    3:不同点是接收参数的方式不同。

    function add(c,d){ return this.a + this.b + c + d;}
    
    var s = {a:1, b:2};
    console.log( add.call(s,3,4) );// 1+2+3+4 =10
    console.log( add.apply(s,[3,4]) ); // 1+2+3+4 =10
     1 window.firstName = "tomF";
     2 window.lastName = "tomL";
     3 var myObj = {firstName:"myF", lastName:"myL"};
     4   
     5 function getName(){ console.log(this.firstName + this.lastName); }
     6   
     7 function getMess(sex, age){ 
     8     console.log(this.firstName + this.lastName+ "性别:"+sex+"age:"+age);
     9 }
    10  
    11 getName.call(window);//tomFtomL
    12 getName.call(myObj);//myFmyL
    13 getName.apply(window);//tomFtomL
    14 getName.apple(myObj);//myFmyL
    15  
    16 getMess.call(window,'girl',21);//tomFtomL性别:girlage:21
    17 getMess.apply(window,['girl',21]);//tomFtomL性别:girlage:21
    18 getMess.call(myObj,'unknown',30);//myFmyL性别:unknownage:30
    19 getMess.apply(myObj,['unknown',30]);//myFmyL性别:unknownage:30
  • 相关阅读:
    面试官:Redis中字符串的内部实现方式是什么?
    面试官:Redis中哈希数据类型的内部实现方式是什么?
    面试官:Redis中列表的内部实现方式是什么?
    java多线程之sleep 与 yield 区别
    JMH:基准测试工具套件应用
    多线程之interrupt与优雅停止一个线程
    java中sleep与 yield 区别
    JUC高并发编程详细教程
    java中线程的6中状态
    手把手教你用Python网络爬虫进行多线程采集高清游戏壁纸
  • 原文地址:https://www.cnblogs.com/ming-os9/p/8945901.html
Copyright © 2020-2023  润新知