在类方法上使用apply()

时间:2018-05-27 01:35:55

标签: class ecmascript-6 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; 

1 个答案:

答案 0 :(得分:2)

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

所以,你可以这样做:

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

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

也许你想要信息是这样的:

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