简体   繁体   English

构造函数中的JS私有函数

[英]JS private function inside Constructor

I'm trying to see if a private function exists inside a constructor based on a string value being passed in. If it does then it should call that private function. 我正在尝试基于传入的字符串值查看构造函数内部是否存在私有函数。如果确实存在,则应调用该私有函数。 I don't want to expose these methods outside the instance with this.intro or this.enter. 我不想使用this.intro或this.enter在实例之外公开这些方法。 Anyone know how I can call the private method based on the string value I pass in. 任何人都知道如何根据传入的字符串值调用私有方法。

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

    }

Create an instance of Animator. 创建一个Animator实例。

var anim = new Animator();
anim.animate('$('.slide'));

the slide div's id is named after the animation type function to call inside Animator instance. 幻灯片div的ID是根据要在Animator实例内部调用的动画类型函数命名的。

Inside your class you can put this command and make a visible some methods 在您的类中,您可以放置​​此命令并使某些方法可见

return{
 _intro : intro
}

Store your private functions as properties of an object, so you can test for their existence: 将私有函数存储为对象的属性,以便您可以测试它们的存在:

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

You could try something like this: 您可以尝试这样的事情:

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

Testing this out like so 像这样测试

var x = new Animator();
x.animate({ attr:function(){ return 'intro'; } })

Succesfully prints "INTRO WORKING" on the console. 在控制台上成功打印“ INTRO WORKING”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM