zoukankan      html  css  js  c++  java
  • javascript call()和apply()

    ECMAScript给Function原型定义了两个方法,一个是call()和apply()。使用这两个方法可以想其他对象方法一样调用函数。把对象当成数据一样的参数传递给函数,参数去调用函数。

    他两的区别是:call的第一个参数必须是对象(或者函数),其余的参数可以任意。而apply的一般只有两个参数,第一个必须是对象或者函数,第二个是一个带下标的集合。

    例如:

    function dow(s){
        document.write("<h1>"+s+"</h1>");
    }
    
    function Point(x,y){
        this.x=x;
        this.y=y;
        
        this.toString=function(){
            return "("+[x,y]+")";
        }
    }
    
    function Vectory(x,y){
        this.x=x;
        this.y=y;
        
        this.toString=function(){
            return "("+[x,y]+")";
        }
    }
    
    function add(x,y){
        return new this.constructor(this.x+x,this.y+y);
    }
    
    var p=new Point(2,4);//实例化一个对象
    var v=new Vectory(3,5);
    //call()方法的作用是把call的第一参数是对象调用call前面的方法,除了call第一个参数以外的所有参数都是真正意义上的参数,传递给call前面的方法体
    
    
    dow(p);
    dow(add.call(p,3,5));//这里实际是把p当成参数传递给add
    dow(add.apply(p,[2,6]));//这里只有两个参数,且第二个参数是一个带下标的数组
  • 相关阅读:
    Codeforces Round #632 (Div. 2)
    Codeforces Round #630 (Div. 2)
    多项式全家桶
    Educational Codeforces Round 84 (Rated for Div. 2)
    【cf1186E】E. Vus the Cossack and a Field(找规律+递归)
    [CF847B] Preparing for Merge Sort
    [CF858D] Polycarp's phone book
    [CF911D] Inversion Counting
    [CF938C] Constructing Tests
    [CF960C] Subsequence Counting
  • 原文地址:https://www.cnblogs.com/Dtscal/p/3696871.html
Copyright © 2011-2022 走看看