Call a JavaScript function name using a string?

前端 未结 10 1114
孤独总比滥情好
孤独总比滥情好 2020-11-30 07:07

How can I hook up an event to a function name I have defined as a string?

I\'m using Prototype.js, although this is not Prototype-speficic.

$(inputId         


        
10条回答
  •  自闭症患者
    2020-11-30 07:38

    update:--- use ES6 export and import

    a.js

    const fn = {
      aaa: function() {
        //code
      },
      bbb: function() {
        //code
      },
      //codes ....
      nnn: function() {
        //code
      }
    }
    
    export default fn
    

    b.js

      import someFn from './a'
      //eg
      const str1='aaa'
      const str2 = 'bbb'
    
      someFn[str1]()
    

    • eval('str') (obsolete feature https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features )

    • setTimeout('str') setInterval('str')

    • window['str'] (but...sometimes,global object is not window)

    • new Function('str')

    These methods above always not be recommend by some reasons, but they are really convenient to use. These methods below are safe, but really not conveninet to use.

    • switch...case (or if...else)

      switch(str){
          case 'str1': 
              fn1()
              break
          case 'str2':
              fn2
              //and so on
      }
      
    • put functions in a object

      const fn={
          str1:fn1,
          str2:fn2
          //and so on
      }
      fn[str1] //call function
      

提交回复
热议问题