0

こんにちは私は動的関数を呼び出す方法のstackoverflowに関する記事を見つけました:

function mainfunc(func) {
    this[func].apply(this, Array.prototype.slice.call(arguments, 1));
}

これはとても便利です。しかし、オブジェクト関数で関数を呼び出すにはどうすればよいですか?

エラーが発生します:

"TypeError:this[func]は未定義ですthis[func] .apply(this、Array.prototype.slice.call(arguments、1));"

次のようになります。

var myScript = {
...
add : function() {
...
myScript.ajax('url.php', params, 'myScript.add2List');
},

add2List : function(data) {
console.log(data);
},

ajax : function(url, params, func) {
  $.ajax({
      type: "POST",
      url: url,
      data: params,
      success: function(data) {
        console.log(func);
        mainfunc(func, data);
      }
  });
 }
}
4

1 に答える 1

0

その関数を使用する必要はありません。代わりに以下を実行できます。

var myScript = {
...
add : function() {
  ...
  myScript.ajax('url.php', params,  this.add2List);
},

add2List : function(data) {
  console.log(data);
},

ajax : function(url, params, func) {
  $.ajax({
      type: "POST",
      url: url,
      data: params,
      success: func
  });
 }
}
于 2012-09-02T11:48:12.360 に答える