List built in JavaScript standard object methods

痞子三分冷 提交于 2021-02-19 06:29:17

问题


Is there a way to list all JavaScript standard object method?

I mean I'm trying to get all the built in methods of String so I was thinking and I did tried doing this:

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

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

But no luck. Also if there is a way that solution should work for all ECMAScript standard classes/objects.

Edit: I want to point out that the solution should work in server side environment also like rhino or node.js.

And as much as possible not using a third party API/framework.


回答1:


Won't dir give you what you need?

console.log(dir(method))

EDIT:

This would work (try John Resig's Blog for more info):

Object.getOwnPropertyNames(Object.prototype) gives :

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

Object.getOwnPropertyNames(Object) gives :

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



回答2:


You should be able to get the list of methods by checking the type of properties as explained here

Also try getOwnPropertyNames




回答3:


I got the answer from this post How to display all methods of an object in Javascript?

Thanks to CiannanSims




回答4:


So here is a way to squeeze out a few more properties:

> 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' ]

I am not a javascript person but I would guess that the reason that this happens is because bind, toString, call and apply might be inherited from higher inheritance levels (does that even make sense in this context?)

EDIT: Btw here is one i implemented that looks as far back in the prototypes as it can.

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;
}


来源:https://stackoverflow.com/questions/15696958/list-built-in-javascript-standard-object-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!