【问题标题】:Calling class functions dynamically动态调用类函数
【发布时间】:2016-03-03 07:53:25
【问题描述】:

如何从它的字符串中调用类函数?

在我检查函数是否存在之后

if(typeof requestName == 'function') {

 }

我需要调用类函数,例如类Foo中的CreateJob。我怎么能这样做?

var Foo = function(credentialsObject){
        this.cred = credentialsObject;
    };

    Foo.prototype.SendRequest = function(requestName,dataObj) {
        // If create requestName, job object exists and credentials have been setup, proceed with a requestName call
        if(requestName && dataObj && (this.cred.userID && this.cred.apiKey)) {
            // Check if the function exists
           if(typeof requestName == 'function') {

           }
        }
    };

    Foo.prototype.CreateJob = function(dataObj) {

    };

    Foo.prototype.CancelJob = function(dataObj) {

    };

    Foo.prototype.JobStatus = function(dataObj) {

    };

【问题讨论】:

    标签: javascript function class object


    【解决方案1】:

    您可以使用bracket notation 来执行此操作,以检查函数是否存在并调用它

    var Foo = function(credentialsObject) {
      this.cred = credentialsObject;
    };
    
    Foo.prototype.SendRequest = function(requestName, dataObj) {
      // If create requestName, job object exists and credentials have been setup, proceed with a requestName call
      if (requestName && dataObj && (this.cred.userID && this.cred.apiKey)) {
        // Check if the function exists
        if (typeof this[requestName] == 'function') {
          this[requestName](dataObj)
        }
      }
    };
    
    Foo.prototype.CreateJob = function(dataObj) {
      snippet.log('create job')
    };
    
    Foo.prototype.CancelJob = function(dataObj) {
    
    };
    
    Foo.prototype.JobStatus = function(dataObj) {
    
    };
    
    var foo = new Foo({
      userID: 'x',
      apiKey: 'y'
    });
    
    foo.SendRequest('CreateJob', {})
    <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

    【讨论】:

      【解决方案2】:

      应该很简单

      if(typeof this[requestName] == 'function') 
      {
         this[requestName] ( dataObj );
      }
      

      【讨论】:

      • 在调用类函数之前我不需要引用this 吗?
      • @aashna 是的,更新了帖子。抱歉忘记添加相同的内容。我认为OP只是询问如何通过名称动态调用函数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      • 2018-02-02
      • 2012-07-17
      • 2011-10-26
      • 1970-01-01
      相关资源
      最近更新 更多