JavaScript - call

159 阅读1分钟

JavaScript中,如果想要改变当前函数调用的上下文对象的时候,我们都会联想到call、apply和bind

// shenmegui...

MDN解释

call() 方法使用一个指定的 this值和单独给出的一个或多个参数来调用一个函数(这里指Product)。

注意:该方法语法和作用于apply()方法类似,只有一个却别,就是call()方法接受一个参数列表,而apply()方法接受一个包含多个参数的数组。

例子理解:

function Product (name, price) {
    this.name = name
    this.price = price
}

function Food (name, price) {
    Product.call(this, name, price)
}

var food =new Food('cheese', 10)

console.log(food.name)


语法

function.call(thisArg, arg1, arg2, ...)

thisArg

可选的。在 function 函数运行时使用的 this 值。请注意,this可能不是该方法看到的实际值:如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象,原始值会被包装。

arg1, arg2, ... 指定的参数列表。

返回值

使用调用者提供的this值和参数调用该函数的返回值。若该方法没有返回值,则返回undefined

描述

call()允许为不同对象分配 分配和调用属于一个对象的函数/方法。 call() 提供新的this值给当前调用的函数/方法。可以使用call来实现继承:写一个方法,然后让新对象来继承它(而不是在新对象中再写一次)。