作为一个长期的经典继承OO程序员,我非常习惯使用构造函数并创建接受所需参数作为构造函数参数的对象.例如,发送与订单相关的警报的对象可能如下所示:
var orderNotifier = function(orderId, notifier, recipients)
{
this.notifyApproved = function()
{
// use the notifier object passed as ctor param to send notifications
// related to orderId to recipients
}
this.notifySomeOtherEvent = function() { // use the ctor params again }
}
// then use it like
var on = new orderNotifier(12345, new BasicNotifier(), someArrayOfEmails);
on.notifyApproved();
Run Code Online (Sandbox Code Playgroud)
这是一个人为的例子,但举例说明了(恕我直言)参数化构造函数的价值.特别:
认识到JavaScript中的构造函数创建模式不能很好地支持信息隐藏,我被立即调用函数表达式(IIFE)模式所吸引,其闭包和更强的访问控制.现在我遇到了这样一个事实:我不能使用IIFE模式传递对象构造参数,或者至少我不明白我是怎么做的.
我知道你可以将参数传递给匿名函数,如下所示:
(function(param){})(someVar);
Run Code Online (Sandbox Code Playgroud)
但这与显式创建新对象并将参数传递给构造函数不同.根据IIFE模式的本质,我不一定要将数据传递给对象.
我上面的IIFE版本就像:
var orderNotifier = (function()
{
var privateHelperMethod = function() { return 'blahblahblah'; };
return {
notifyApproved: function(orderId, notifier, recipient)
{
// use the notifier object passed as ctor param to send notifications
// related to orderId to recipients
var msg = privateHelperMethod()
},
notifySomeOtherEvent: function(orderId, notifier, recipient)
{
// use the ctor params again
var msg = privateHelperMethod();
}
};
}}();
Run Code Online (Sandbox Code Playgroud)
因此,我必须要求经验丰富,渐进的JavaScript专家:使用标准的ECMAScript 5语言功能,使用IIFE模式创建对象并在单个操作中提供对象状态的最佳实践(或者甚至可能只是常见做法)是什么?(除了暴露一个setState()或类似的方法.)换句话说:我怎么能吃蛋糕并吃掉它?
jfr*_*d00 11
您的IIFE构造函数模式创建一个单例(只有一个对象).它不公开构造函数,因此不能用于创建更多对象.因此,您可以通过IIFE的参数将您想要的任何信息传递到单例中,或者只是将这些参数编码到实现中.
这就是为什么我希望你向我们展示你实际谈论的是什么样的设计模式,因为这个特定的模式不是通用的构造函数,并且不是为了创建多个对象而设计的.它创建一个单例对象.这就是最好的.如果返回的对象公开了可以用作构造函数的函数,那么它们可以像其他构造函数一样获取参数.
我这里没有看到问题.我没有看到有一个问题需要解决.
根据您的意见,如果您想将非静态数据传递到IIFE,那么您必须在创建非静态数据后找到IIFE(以便在IIFE运行之前数据可用),选择不同的设计模式(例如使用传统的构造函数)或使用创建构造函数的IIFE(稍后可以调用),而不是对象.
例如,这是一个创建构造函数的IIFE:
var OrderNotifier = (function()
{
// private stuff would go here
// shared by all instances
return function(/* constructor args go here */) {
// per-instance private vars here
return {
notifyApproved: function(orderId, notifier, recipient)
{
// use the notifier object passed as ctor param to send notifications
// related to orderId to recipients
},
notifySomeOtherEvent: function(orderId, notifier, recipient)
{
// use the ctor params again
}
};
}
}}();
// sometime later in your code
var notifier = new OrderNotifier(/* args here */);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3326 次 |
| 最近记录: |