动态调用类函数

时间:2016-03-03 07:53:26

标签: javascript function class object

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

检查功能是否存在后

if(typeof requestName == 'function') {

 }

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

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

    };

2 个答案:

答案 0 :(得分:3)

您可以使用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>

答案 1 :(得分:2)

应该像

一样简单
if(typeof this[requestName] == 'function') 
{
   this[requestName] ( dataObj );
}