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

    介绍

    有编程开发经验的都知道函数有作用域这种东西,JavaScript中的函数中的亦是如此。但是想要更改该函数的作用域,最方便的方式就是通过apply和call方法

    用法

    apply和call在功能上是相同的,但是唯一的不同之处在于提供参数的方式。

    1. apply使用参数数组而不是一组参数列表

      window.color = "red";
      var a = {
        color : "blue"
      };
      var x = function(){
        alert(this.color+"--"+arguments.length);
      }
      x();//red is 0
      x.apply(window);//red is 0
      x.apply(a,[1,2,3]);//blue is 3
      

    2. call使用时参数列表

      window.color = "red";
      var a = {
        color : "blue"
      };
      var x = function(){
        alert(this.color+" is "+arguments.length);
      }
      x();//red is 0
      x.call(window);//red is 0
      x.call(a,1,2,3);//blue is 3
      

    1.apply语法

    fun.apply(thisArg[, argsArray])
    

    参数

    • thisArg

      fun 函数运行时指定的 this 值。需要注意的是,指定的 this 值并不一定是该函数执行时真正的 this 值,如果这个函数处于非严格模式下,则指定为 nullundefined会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的 this 会指向该原始值的自动包装对象。

    • argsArray

      一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 fun 函数。如果该参数的值为null 或 {{jsxref("Global_Objects/undefined", "undefined")}},则表示不需要传入任何参数。从ECMAScript 5 开始可以使用类数组对象。浏览器兼容性请参阅本文底部内容。

    2.call语法

    fun.call(thisArg[, arg1[, arg2[, ...]]])
    

    参数

    • thisArg

      fun函数运行时指定的this需要注意的是,指定的this值并不一定是该函数执行时真正的this值,如果这个函数处于非严格模式下,则指定为nullundefinedthis值会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的this会指向该原始值的自动包装对象。

    • arg1, arg2, ...

      指定的参数列表。

  • 相关阅读:
    zoj 1239 Hanoi Tower Troubles Again!
    zoj 1221 Risk
    uva 10192 Vacation
    uva 10066 The Twin Towers
    uva 531 Compromise
    uva 103 Stacking Boxes
    稳定婚姻模型
    Ants UVA
    Golden Tiger Claw UVA
    关于upper、lower bound 的探讨
  • 原文地址:https://www.cnblogs.com/olddoublemoon/p/6602565.html
Copyright © 2011-2022 走看看