Javascript 构造函数内的JS私有函数
我试图根据传入的字符串值查看构造函数中是否存在私有函数。如果它这样做了,那么它应该调用这个私有函数。我不想使用this.intro或this.enter在实例外部公开这些方法。 任何人都知道如何根据传入的字符串值调用私有方法Javascript 构造函数内的JS私有函数,javascript,oop,Javascript,Oop,我试图根据传入的字符串值查看构造函数中是否存在私有函数。如果它这样做了,那么它应该调用这个私有函数。我不想使用this.intro或this.enter在实例外部公开这些方法。 任何人都知道如何根据传入的字符串值调用私有方法 function Animator(){ this.animate = function( slide ){ var type = slide.attr('id'); if (typeof [typ
function Animator(){
this.animate = function( slide ){
var type = slide.attr('id');
if (typeof [type] == 'function'){
console.log("function");
//call [type]()
}else{
console.log("nope string = ", [type]);
}
}
var intro = function(){
console.log("INTRO WORKING");
}
var enter = function(){
console.log("ENTER");
}
}
创建Animator的实例
var anim = new Animator();
anim.animate('$('.slide'));
slide div的id是以animation type函数命名的,用于调用内部Animator实例。在类中,您可以使用此命令并在某些方法中显示一个视图
return{
_intro : intro
}
将私有函数存储为对象的属性,以便测试它们是否存在:
var private = {
intro: function(){
console.log("INTRO WORKING");
},
enter: function(){
console.log("ENTER");
}
}
this.animate = function( slide ){
var type = slide.attr('id');
if (private[type]) {
private[type].apply(this, slide)
}
}
您可以尝试以下方法:
function Animator(){
this.animate = function( slide ){
var type = slide.attr('id');
if (typeof privates[type] == 'function'){
console.log("function");
privates[type]();
}else{
console.log("nope string = ", type);
}
}
var privates = {
intro: function(){
console.log("INTRO WORKING");
},
enter: function(){
console.log("ENTER");
}
}
}
像这样测试一下
var x = new Animator();
x.animate({ attr:function(){ return 'intro'; } })
在控制台上成功打印简介。您不应该使用var slide=slide仅供参考。幻灯片已定义。这将使该方法可在承包商之外访问。正如我说的,我不想那样做。