zoukankan      html  css  js  c++  java
  • javascript call apply



    call 和 apply 都是为了改变某个函数运行时的 context 即上下文而存在的,换句话说,就是为了改变函数体内部 this 的指向。因为 JavaScript 的函数存在「定义时上下文」和「运行时上下文」以及「上下文是可以改变的」这样的概念。

    二者的作用完全一样,只是接受参数的方式不太一样。例如,有一个函数 func1 定义如下:
    var func1 = function(arg1, arg2) {};
    就可以通过 func1.call(this, arg1, arg2); 或者 func1.apply(this, [arg1, arg2]); 来调用。其中 this 是你想指定的上下文,他可以任何一个 JavaScript 对象(JavaScript 中一切皆对象),call 需要把参数按顺序传递进去,而 apply 则是把参数放在数组里。

    JavaScript 中,某个函数的参数数量是不固定的,因此要说适用条件的话,当你的参数是明确知道数量时,用 call,而不确定的时候,用 apply,然后把参数 push 进数组传递进去。当参数数量不确定时,函数内部也可以通过 arguments 这个数组来便利所有的参数
     
    应用场景
     
              1.例如求最大值:arr = [3,23,4,88,2.5,1,5,7,89]; alert(Math.max.apply(Math,arr));
              2.事件绑定
     
     
    对象冒充原型不可以继承
    只能用prototype
    function fruits() {
                this.name = "水果";
            };
            fruits.prototype = {

                say: function () {
                    console.log("吃-------" + this.name);
                }

            }

            var pg = {
                name: "苹果"
            }


            var a = new fruits();

            fruits.prototype.say.call(pg);
            //pg.say();
            //a.say();

    数组之间追加

    var array1 = [12 , "foo" , {name:"Joe"} , -2458]; 
    var array2 = ["Doe" , 555 , 100]; 
    Array.prototype.push.apply(array1, array2); 
    // array1 值为  [12 , "foo" , {name:"Joe"} , -2458 , "Doe" , 555 , 100] 

    获取数组中的最大值和最小值

    var  numbers = [5, 458 , 120 , -215 ]; 
    var maxInNumbers = Math.max.apply(Math, numbers),   //458
        maxInNumbers = Math.max.call(Math,5, 458 , 120 , -215); //458
     
     
  • 相关阅读:
    冒泡排序
    选择排序
    1069 微博转发抽奖 (20 分)
    动态规划-石子合并
    动态规划-最长公共子序列
    动态规划-最长上升子序列
    动态规划-数字三角形
    动态规划-分组背包问题
    动态规划-多重背包问题
    动态规划-完全背包问题
  • 原文地址:https://www.cnblogs.com/jentary/p/6277162.html
Copyright © 2011-2022 走看看