什么更适用于表达/收集对象行为,IIFE或对象构造函数的变体?,因为它适用于发布/订阅模式。
是选择只使用一种样式还是另一种样式,还是我没有考虑下面所分享的其他好处/缺点?
(我更喜欢通过YDKJS ch.6“ this and objects”的Kyle Simpson行为委派样式进行OLOO操作。)
好处
缺点
好处
从Addy Osmani链接到simple pub/sub IIFE pattern
// pubsub implementation, mine
let pubsub = {
topics: {},
publish: function ( topic, message ) {
if (this.topics.hasOwnProperty(topic)) {
// add message to topic and update # messages in topic
this.topics[topic].messages.push(message)
this.topics[topic].messages.count = this.topics[topic].messages.count++;
} else {
// create new topic object
this.topics[topic] = {}
this.topics[topic].subscribers = []
this.topics[topic].messages = []
this.topics[topic].count = 1
}
},
subscribe: function ( entityID, topic ) {
// if topic exists, add entity to list of subscriptions for that topic
if (this.topics.hasOwnProperty(topic)) {
this.topics[topic].subscribers.push(entityID)
} else {
throw new TypeError("the topic must exist first before subscribing to it")
}
},
unsubscribe: function ( entityID, topic ) {
if (this.topics.hasOwnProperty(topic)) {
if (this.topics[topic].subscribers.includes(entityID)) {
for (let i = 0, j = this.topics[topic].subscribers.length; i < j; i++) {
if (this.topics[topic].subscribers[i] === entityID) {
this.topics[topic].subscribers.splice(i, 1);
}
}
} else {
throw new TypeError("an entity must be subscribed to the topic before unsubscribing")
}
} else {
throw new TypeError("the topic must exist first before unsubscribing from it")
}
},
}
let pubsubInstance = Object.create(pubsub)
pubsubInstance.subscribe(object, topic)
或
/*!
* Pub/Sub implementation
* http://addyosmani.com/
* Licensed under the GPL
* http://jsfiddle.net/LxPrq/
*/
;(function ( window, doc, undef ) {
'use strict';
var topics = {},
subUid = -1,
pubsubz ={};
pubsubz.publish = function ( topic, args ) {
if (!topics[topic]) {
return false;
}
setTimeout(function () {
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
};
pubsubz.subscribe = function ( topic, func ) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = (++subUid).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
pubsubz.unsubscribe = function ( token ) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return false;
};
var getPubSubz = function(){
return pubsubz;
};
window.pubsubz = getPubSubz();
}( this, this.document ));
答案 0 :(得分:0)
我认为这是关于您如何在一天结束时阅读代码的。另外,如果我没记错的话,babel / webpack还是将其转换为IIFE进行转译/串联;如果我错了,有人纠正我。