首页 > 解决方案 > 在类方法上使用 apply()

问题描述

是否可以在类方法上调用 apply() 方法?我目前收到一个未定义的值。我正在寻找“Todd 是 Jason、Karla 和 David 的父亲”的输出。

class Person {
  constructor(name) {
    this._name = name;
  }
  get name() {
    return this._name;
  }
  set name(newValue) {
    this._name = newValue;
  }
  info() {
    return this._name + " is the father of " + children;
  }
}

var children = ["Jason ", " Karla", " and David"];

var e1 = new Person("Todd");

var ref = e1.info.apply(e1.name, children)

document.querySelector(".test").innerHTML = ref; 

标签: classecmascript-6apply

解决方案


要使用.apply(),您需要向它传递两个参数。第一个是您要调用该方法的对象。在您上面的情况下,那将是e1. 第二个参数是要传递给方法的参数数组。

所以,你可以这样做:

var ref = e1.info.apply(e1, children);

但是,您的info方法并不正确。如果您要将参数传递给info()with .apply(),那么您可能应该使用这些参数以及它现在的编写方式,它试图将一个全局数组添加到一个不正确的字符串,这有几个原因。

也许您希望信息是这样的:

info(...args) {
   return this._name + " is the father of " + args.join(",");
}

推荐阅读