Can I pass array in Function.call() method in javascript?

时间:2018-03-31 07:37:35

标签: javascript

Take a look at the following code:

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

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

console.log(new Food('cheese', 5).name);
// expected output: "cheese"

So, my question is can we pass an array to the call method as a parameter as like the apply method

1 个答案:

答案 0 :(得分:0)

如果你想call有意义,你只能在你正在调用的函数接受某个数组作为参数的情况下这样做。

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

function Food(name, price) {
  Product.call(this, name, price, ['a', 'b', 'c']);
  this.category = 'food';
}

console.log(new Food('cheese', 5).arrInfo);

您可以传入单个对象,以获得更类似于命名参数的效果,如果这是您正在寻找的内容:

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

function Food(name, price) {
  Product.call(this, { name, price, someArr: ['a', 'b', 'c'] });
  this.category = 'food';
}

console.log(new Food('cheese', 5).arrInfo);

这样,您只需将this以外的单个变量(对象的引用)传递给.call