我在 Javascript 中看到了下面的代码行,但我不知道这种方式在制作对象和函数时的名称?
您能否提示如何编写由下面的行调用的对象/函数?
var generalSettings = new (invoke("settings"))({"a":1}).push(5);
我无法对此进行搜索,我在 Javascript 中阅读了有关 OOP 的信息,但从未见过。
谢谢你的帮助!
我在 Javascript 中看到了下面的代码行,但我不知道这种方式在制作对象和函数时的名称?
您能否提示如何编写由下面的行调用的对象/函数?
var generalSettings = new (invoke("settings"))({"a":1}).push(5);
我无法对此进行搜索,我在 Javascript 中阅读了有关 OOP 的信息,但从未见过。
谢谢你的帮助!
在这里,invoke("settings")返回一个构造函数。反过来,该构造函数接收一个参数:对象{"a":1}。最后,由该构造函数生成的结果对象push调用其方法。
// this accepts an object with an `a` key, like {"a":1}
// it constructs an object with an `aVal` property and `push` method
function SettingsObj(options) {
this.aVal = options.a;
this.push = function() { /* ... */ };
}
// this object serves as a dictionary of constructors
var constructors = {
"settings": SettingsObj
}
// this function returns a constructor from the constructors dictionary
function invoke(constructorName) {
return constructors[constructorName];
}
invoke("settings")- 返回一个构造函数new (invoke("settings"))()- 不带参数运行构造函数new (invoke("settings"))({"a":1}) - 运行构造函数一个{"a":1}参数new (invoke("settings"))({"a":1}).push(5)- 调用push构造函数构建的对象上的方法