class - 在类方法上使用 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;
解决方案
要使用.apply()
,您需要向它传递两个参数。第一个是您要调用该方法的对象。在您上面的情况下,那将是e1
. 第二个参数是要传递给方法的参数数组。
所以,你可以这样做:
var ref = e1.info.apply(e1, children);
但是,您的info
方法并不正确。如果您要将参数传递给info()
with .apply()
,那么您可能应该使用这些参数以及它现在的编写方式,它试图将一个全局数组添加到一个不正确的字符串,这有几个原因。
也许您希望信息是这样的:
info(...args) {
return this._name + " is the father of " + args.join(",");
}
推荐阅读
- android - 致命异常:.commit() 期间 FragmentManager Transaction 的 Main
- python - 尝试连接 daphne websocket nginx 时收到 502
- javascript - .find() 不是 mongoose + nodejs 中的函数
- java - 使用活动目录自动验证 java 或 .net 应用程序中的用户
- python - 如何解决仅在 Jenkins 中出现的 JSON 解码错误?
- json - 如何将循环创建的 jsonObjects 放入 jsonArray 并在 jsonArray 中获取响应?
- docker - 设置 Pod 重启限制
- c# - 添加新 TabItem 时更改 TabControl SelectedIndex
- r - 当我看到视图时得到正确的对齐(data.frame)
- android - 自定义 ArrayAdapter 只显示一个对象