2013-03-29 14 views
2

有沒有辦法列出所有JavaScript標準對象方法?使用JavaScript標準對象方法建立的列表

我的意思是,我試圖讓所有的內置,所以我想字符串的方法,我也試着這樣做:

for(var method in String) { 
    console.log(method); 
} 

// I also tried this: 
for(var method in String.prototype) { 
    console.log(method); 
} 

,但沒有運氣。此外,如果有解決方案應該適用於所有ECMAScript標準類/對象的方法。

編輯: 我想指出解決方案應該可以在服務器端環境中工作,如rhino或node.js.

並儘可能不使用第三方API /框架。

+0

可能重複:http://stackoverflow.com/a/152573/875127 –

+0

@CiananSims我想,也許不會,因爲這更多的是對內置類。這個問題的答案不適用於這個問題。 –

+2

我明白了。請問http://stackoverflow.com/q/2257993/875127擺脫任何光?看起來是一個令人驚訝的不平凡的問題。 –

回答

5

不會dir給你你需要什麼?

console.log(dir(method)) 

編輯:

這會工作(嘗試John Resig's Blog獲取更多信息):

Object.getOwnPropertyNames(Object.prototype)給出:

["constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "__defineGetter__", "__lookupGetter__", "__defineSetter__", "__lookupSetter__"] 

Object.getOwnPropertyNames(Object)給出:

["length", "name", "arguments", "caller", "prototype", "keys", "create", "defineProperty", "defineProperties", "freeze", "getPrototypeOf", "getOwnPropertyDescriptor", "getOwnPropertyNames", "is", "isExtensible", "isFrozen", "isSealed", "preventExtensions", "seal"] 
+0

方法dir返回undefined。我在想什麼就像一個函數或某種程序,將返回一個內置的方法數組。 –

+0

請看編輯 – loxxy

+0

我不能接受我自己的答案,所以我會接受你的:D –

0

您應該能夠通過檢查屬性的類型來獲得的方法列表作爲解釋here

也可以嘗試getOwnPropertyNames

+0

是的,我的例子和答案是類似的。我只需要添加一個測試條件,如果它是一個函數或不,但據我觀察它不會工作。 –

+1

好的試用版2。檢查getOwnPropertyNames – Brian

0

所以這裏有一個方法可以擠出更多的屬性:

> function a() {} 
undefined 
> Object.getOwnPropertyNames(a) 
[ 'length', 
    'name', 
    'arguments', 
    'caller', 
    'prototype' ] 
> a.bind 
[Function: bind] 
> // Oops, I wanted that aswell 
undefined 
> Object.getOwnPropertyNames(Object.getPrototypeOf(a)) 
[ 'length', 
    'name', 
    'arguments', 
    'caller', 
    'constructor', 
    'bind', 
    'toString', 
    'call', 
    'apply' ] 

我不是一個javascript的人,但我猜,出現這種情況的原因是因爲bindtoStringcallapply可能會從更高的產業層面繼承(沒有,即使道理在這方面?)

編輯:順便說一句,這是我實現的一個看起來儘可能早在原型。

function getAttrs(obj) { 
    var ret = Object.getOwnPropertyNames(obj); 
    while (true) { 
     obj = Object.getPrototypeOf(obj); 
     try { 
      var arr = Object.getOwnPropertyNames(obj); 
     } catch (e) { 
      break; 
     } 

     for (var i=0; i<arr.length; i++) { 
      if (ret.indexOf(arr[i]) == -1) 
       ret.push(arr[i]); 
     } 
    } 

    return ret; 
} 
相關問題