【发布时间】:2012-08-14 14:49:38
【问题描述】:
由WSFunctions[this.name](); 执行的第二个console.log() 将打印undentified。我想知道我是否能够以某种方式在我的Call() 函数中使用inherit DoThisAndThat。我不想以WSFunctions[this.name](this.params) 的方式传递参数,因为随着项目的发展,可能有超过this.params 可以传递。
function WS(name, params) {
this.name = name;
this.params = params;
}
WS.prototype.Call = function() {
if (typeof WSFunctions[this.name] !== "function") {
return false;
}
console.log(this.params);
WSFunctions[this.name]();
return true;
}
var WSFunctions = {
'ScreenRightGuest': function() {
// .. whatever ..
return true;
},
'DoThisAndThat': function() {
console.log(this.params);
return true;
}
}
new WS('DoThisAndThat', { login: '123', pass: 'abc' }).Call();
提前致谢 迈克
【问题讨论】:
-
或者你可能有不同的建议如何构建它,我只是从 JavaScript“类”开始。
-
这实际上与“类”或继承或原型无关,仅与
this和调用函数的工作方式有关, -
是的,这是一个非常奇怪的模式。您正在构建一个对象的实例,并使用该对象的“属性”来引用该类型的“静态函数”。
-
这个想法是将来只需添加新功能就可以自定义
var WSFunctions。此外,它们将使用 new WS('name',) 调用。有 Call() 作为原型,将来还会有更多,Reload()、Copy() 等 -
将
WSFunctions作为外部依赖似乎仍然很奇怪。您也应该将它们分配给原型,或者将它们作为参数传递给WS。
标签: javascript function object inheritance prototype