根据对象创建期间的参数选择对象具有哪一组方法 - JavaScript
我已经搜索和阅读了几个小时,但我仍然无法理解创建一个新对象的基本设计模式,该对象可以选择不同的方法(同名),这些方法是根据参数之一设置的。这是一些代码来解释我想要做什么。 欢迎所有建议和替代方法。我希望有人能把我从无知的阴云中解放出来。 谢谢
function BaseConstructor(whichMethods) {
if (whichMethods==='a') {
// do something to incorporate methodSetA
}
else if (whichMethods==='b') {
// do something to incorporate methodSetB
}
this.init();
};
var methodSetA = {
init: function() {
// do initialisation A way
},
speak: function() {
alert('i speak AAA way')
}
};
var methodSetB = {
init: function() {
// do initialisation B way
},
speak: function(){
alert('i got BBB all the way')
}
};
thing = new BaseConstructor('b');
// b is an instance of BaseConstructor and has done the bWay init() function
thing.speak() // return alert 'i got BBB all the way'
I have searched and read for a few hours yet I still cant understand the basic design pattern for creating a new object that has a choice of different methods (of the same name) that is set dependant on one of the arguments. here's some code to explain what I am trying to do.
All advice and alternative approaches welcome. I hope someone can emancipate me form this cloud of ignorance.
Thanks
function BaseConstructor(whichMethods) {
if (whichMethods==='a') {
// do something to incorporate methodSetA
}
else if (whichMethods==='b') {
// do something to incorporate methodSetB
}
this.init();
};
var methodSetA = {
init: function() {
// do initialisation A way
},
speak: function() {
alert('i speak AAA way')
}
};
var methodSetB = {
init: function() {
// do initialisation B way
},
speak: function(){
alert('i got BBB all the way')
}
};
thing = new BaseConstructor('b');
// b is an instance of BaseConstructor and has done the bWay init() function
thing.speak() // return alert 'i got BBB all the way'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用工厂函数(为您创建适当对象的常规函数)来执行此操作:
并将其作为常规函数调用来调用:
注意:
new
不能与一起使用>BaseConstructor()
因为它是常规函数调用。You can do it like this using a factory function (a regular function that creates the appropriate object for you):
And invoke it as a regular function call:
Note: there is no use of
new
withBaseConstructor()
as it's a regular function call.好吧,要使用“方法集”按照自己的方式进行操作,您可以迭代并复制到
this
(这是一个演示):不过,就我个人而言,我更愿意直接分配给
this
。Well, to do it your way using "method sets," you can iterate and copy into
this
(here's a demo):Personally, though, I'd prefer to assign directly to
this
.您正在寻找工厂模式。
例子:
You are looking for factory pattern.
Example: