zoukankan      html  css  js  c++  java
  • js的apply 和 call

    总是没搞明白js的apply 和call,看到一篇文章+评论,终于搞明白了,记录下来

    http://uule.iteye.com/blog/1158829

    call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 
    上述一个句号一个意思,体现在方向不同。第一个借用别人的函数,第二个借用别人的上下文环境。

    function add(a,b)
    {
        alert(a+b);
    }
    function sub(a,b)
    {
        alert(a-b);
    }
    
    add.call(sub,3,1);  //4
    个人理解call和apply的作用就是切换函数的对象上下文

    “这个例子中的意思是将add执行的上下文由window切换为sub,即this指向是从window变为sub。
     
    修改上述例子:
    function add(a,b)  
    {  
        this(a,b);
        alert(a+b);  
    }  
    function sub(a,b)  
    {  
        alert(a-b);  
    }  
      
    add.call(sub,3,1);  //2    4

    先打出2 然后 为4 ,可说明了:将add执行的上下文由window切换为sub,即this指向是从window变为sub。

    再附其另一例子

    function Animal(){    
        this.name = "Animal";    
        this.showName = function(){    
            alert(this.name);    
        }    
    }    
      
    function Cat(){    
        this.name = "Cat";    
    }    
       
    var animal = new Animal();    
    var cat = new Cat();    
        
    animal.showName.call(cat,",");    //cat
    //animal.showName.apply(cat,[]);

    //通过call或apply方法,将animal的执行上下文改为cat,及此时animal.showName() 中的this指向cat,所以输出结果为‘Cat’

    顺便记录下 javascript语言精粹上看到的一个例子

    用来区分数组和对象(因为js的数组其实就是对象:var a=[];typeof(a)  //"object")

    var is_array = function(value) {
        return Object.prototype.toString.apply(value) === '[object Array]';     
    };
    var a=[];Object.prototype.toString.apply(a)
    //"[object Array]"
    var a=[];a.toString()
    //""
    var a=[];Object.prototype.toString(a)
    //"[object Object]"
  • 相关阅读:
    Android新手之旅(5) 网络资源
    Android新手之旅(10) 嵌套布局
    vertest
    Android新手之旅(4) 通过HTTP访问web
    Android新手之旅(6) 与.Net不同之处
    Android新手之旅(7) RadioButton的自定义
    Android新手之旅(9) 自定义的折线图
    Android新手之旅(8) ListView的使用
    ECLIPSE 安装及与CDT 的使用 多线程编程
    Eclipse的代码提示背景是黑色
  • 原文地址:https://www.cnblogs.com/xnn1993/p/7597426.html
Copyright © 2011-2022 走看看