我正在创建一个基于各种Transition对象转换幻灯片的图库:
window.myGallery = (function () {
var instance = null;
....
//Base Transition
function Transition(slide, settings){
this.slide = slide;
this.el = slide.el;
this.settings = settings;
this.duration = (this.settings['transitionSpeed'] / 1000) + 's';
this.endAnimation = null;
}
//FADE TRANSITION
function FadeTransition(slide, settings){
Transition.call(this, slide, settings);
}
FadeTransition.prototype = Object.create(Transition.prototype);
FadeTransition.prototype.constructor = FadeTransition;
//SLIDE TRANSITION
function SlideTransition(slide, settings){
Transition.call(this, slide, settings);
}
SlideTransition.prototype = Object.create(Transition.prototype);
SlideTransition.prototype.constructor = SlideTransition;
为了获得适当的过渡对象,我构建了这个工厂:
var TransitionFactory = function () {
return {
createTransition: function (slide, transitionType, settings) {
if (transitionType) {
type = transitionType;
}
if (type == 'fade') {
return new FadeTransition(slide, settings);
}
else if(type == 'slide'){
return new SlideTransition(slide, settings);
}
},
//Set default transition
type: "fade"
};
};
由于我设想了几十种不同的转换,我认为我会聪明并接受一个字符串来动态创建转换对象:
createTransition: function (slide, transitionType, settings) {
if (transitionType) {
type = transitionType;
}
type = type.charAt(0).toUpperCase() + type.slice(1);
type += 'Transition';
if(typeof window[type] != 'undefined') //BOOM
return new window[type](slide, settings);
else
return new FadeTransition(slide, settings);
},
问题是FadeTransition
是在分配给window.myGallery
的IIFE中定义的,因为我不想用我的所有对象污染全局范围。因此,这将永远是undefined
:
if(typeof window[type] != 'undefined')
如何在IIFE范围内测试对象的存在并在其存在时进行实例化?
答案 0 :(得分:1)
我对这个问题的理解是你做了类似
的事情window.foo = (function () {
function Fizz() {
return buzz();
}
function buzz() {
return 'fizzbuzz';
}
return Fizz;
}());
你要问
如何在 IIFE 之外进行
buzz();
?
好吧,除非你在 IIFE 中传递buzz
的引用,但这不会发生在这里,你不能。
但是,在 JavaScript 中,您几乎可以使用 Object 之类的所有内容,这可以让您在不污染名称空间的情况下传递引用。
Fizz.buzz = buzz; // before return Fizz
现在,您可以buzz
访问window.foo.buzz
。如果您仍然对此不满意,因为它是功能上的属性,请使用对象作为命名空间
return {
"Fizz": Fizz,
"buzz": buzz
};
答案 1 :(得分:0)
我不确定是否可以在IIFE中访问内部函数,但如果我这样做,我会在对象中添加所有这些函数,根据用户的输入我会从对象中选择函数。这是一个示例实现。
var myGallery = (function() {
var instance = null;
//NOTE: Base Transition Function goes here
function inheriter(child, parent) {
child.prototype = Object.create((parent || Transition).prototype);
child.prototype.constructor = child;
}
var transitions = {
FadeTransition: function(slide, settings) {
Transition.call(this, slide, settings);
},
SlideTransition: function(slide, settings) {
Transition.call(this, slide, settings);
}
};
for (var transition in transitions) {
inheriter(transitions[transition], Transition);
}
return {
createTransition: function(slide, transitionType, settings) {
type = (transitionType || "fade") + "Transition";
type = type.charAt(0).toUpperCase() + type.slice(1);
if (!transitions[type]) {
type = "FadeTransition";
}
return new transitions[type](slide, settings);
}
};
})();