20190725笔记apply详解

3次阅读

共计 1474 个字符,预计需要花费 4 分钟才能阅读完成。

学了那么久前端,对 apply、call 这两个函数的用法,还不是很掌握。
今天看了很多网上的文章,我总结和归纳下用法。

Function.prototype.apply()

apply() 方法调用一个具有给定 this 值的函数,以及作为一个数组(或类似数组对象)提供的参数。

语法

func.apply(thisArg, [argsArray])

参数

  • thisArg /// 这个对象将替代 func 类里的 this 对象
    可选, 在 func 函数运行时使用的 this 值。请注意,this 可能不是该方法看到的实际值:如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象,原始值会被包装。
  • argsArray // 数组、类数组。它将作为参数传到 func 函数中
    可选的。一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 func 函数。如果该参数的值为 null 或 undefined,则表示不需要传入任何参数。从 ECMAScript 5 开始可以使用类数组对象。

返回值

调用有指定 this 值和参数的函数的结果。

示例

var array=['a','b'],
elem=[1,2,3];

array.push.apply(arry,elem);
console.log(array) // ["a","b",1,2,3]
//   定义一个 Animals
    function Animals(name, kind) {
      this.name = name
      this.kind = kind
    }

    // 定义一个猫
    function Cat(name, kind, sex) {Animals.apply(this, arguments)
      console.log(this)  // 
      this.sex = sex
    }

    var HelloKitty = new Cat('Kitty','cat', 'Female')
    console.log(HelloKitty)

最后得到的值:

这是为什么呢?

Animals.apply(this, arguments)
  • this
    表示的是当前 fn 内的 this,就是 Cat 的 this
  • arguments
    表示的是当前 fn 内的所传参数,即'Kitty','cat', 'Female'

当参数 'Kitty','cat', 'Female' 传入 Cat 中,函数利用 apply 函数执行 Animals 的内容,就是将 this.name =name; this.kind = kind; 作用于 Cat 函数内部。

更简单的讲就是将 thisarguments传入 Person 函数执行。

现在我们来做一些改变

    function Animals(name, kind) {
      this.name = name
      this.kind = kind
    }

    // 定义一个猫
    function Cat(name, sex, kind) {Animals.apply(this, arguments)

      this.sex = sex
    }

    var HelloKitty = new Cat('Kitty', 'Female', 'cat')
    console.log(HelloKitty)
  </script>

我们将 Cat 中的 sexkind 换个位置,会得到什么结果呢?

这样就能直观展现出这个过程

   Animals.apply(this,['Kitty', 'Female'])

然后进行赋值

    this.name = 'Kitty'
    this.kind = 'Female'
    

这里的 this 指的是 Cat 对象,赋值成功后,返回 Cat 函数,进行下一步

    this.sex ='Female';

最后得到结果

{
    name: "Kitty", 
    kind: "Female", 
    sex: "Female"
}

正文完
 0