0

例如; 函数alertwriteln;如何在 JavaScript 中以编程方式找到这些函数来自哪个接口?

4

3 回答 3

0

If you want to "list an objects functions", you can do:

function listOwnMethods(obj) {
  var ownMethods = [];

  for (var p in obj) {

    if (obj.hasOwnProperty(p) && typeof obj[p] == 'function') {
      ownMethods.push(p);
    }  
  }
  return ownMethods;
}

However, this will not list the non–enumerable properties. If you want to also get enumerable inherited methods, remove the hasOwnProperty test.

Some versions of JavaScript also have getters and setters, so properties may behave like functions even though their Type is not "function". Finally, host objects can return anything they like when tested with typeof, so you may not be able to determine all (or even any) of a host object's methods that way.

于 2013-10-22T22:44:44.507 回答
0

是的,像这样:

if (typeof(yourFunction) !== "undefined") { 
    // do something, like call the function
}
于 2013-10-22T22:28:16.337 回答
0

您可以轻松检查是否定义了一个函数typeof

if (typeof(maybeFunction) === "function") {
    // do something
}

另一方面,一般来说,要知道函数在哪里定义并不容易。不同的浏览器在不同的地方托管它们的核心功能实现,而且复制对函数的引用非常容易:

var myAlert = alert;    // Now myAlert is a function,
// but where will you find a function myAlert() declaration? Nowhere...

所以我认为你的问题的正确答案是,这是不可能的(一般来说)。您可以使用调试器即时找到它,或者使用良好的文本编辑器或 grep 工具离线查找它,但您将无法以编程方式找到它。

于 2013-10-22T22:30:57.650 回答