构造函数中的JS私有函数

时间:2014-04-09 20:02:58

标签: javascript oop

我试图根据传入的字符串值来查看构造函数中是否存在私有函数。如果是,那么它应该调用该私有函数。我不想用this.intro或this.enter在实例之外公开这些方法。 任何人都知道如何根据我传入的字符串值调用私有方法。

 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'));

幻灯片div的id以动画类型函数命名,以便在Animator实例中调用。

3 个答案:

答案 0 :(得分:0)

在你的课程中你可以放置这个命令并使一些方法可见

return{
 _intro : intro
}

答案 1 :(得分:0)

将您的私有函数存储为对象的属性,以便您可以测试它们的存在:

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)
  }
}

答案 2 :(得分:0)

您可以尝试这样的事情:

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'; } })

成功打印" INTRO WORKING"在控制台上。

相关问题