3

If I have var foo = 'bar';, how do I get all the functions callable on foo, such as toUpperCase? It's not an object, so Object.getOwnPropertyNames(foo) doesn't work:

$ node
> var foo = 'bar';
undefined
> console.log(Object.getOwnPropertyNames(foo));
TypeError: Object.getOwnPropertyNames called on non-object
    at Function.getOwnPropertyNames (native)
    at repl:1:20
    at REPLServer.eval (repl.js:80:21)
    at repl.js:190:20
    at REPLServer.eval (repl.js:87:5)
    at Interface.<anonymous> (repl.js:182:12)
    at Interface.emit (events.js:67:17)
    at Interface._onLine (readline.js:162:10)
    at Interface._line (readline.js:426:8)
    at Interface._ttyWrite (readline.js:603:14)

katspaugh's simple, elegant solution:

> console.log(Object.getOwnPropertyNames(foo.constructor.prototype));
[ 'constructor',
  'length',
  'toLowerCase',
  ... ]
undefined
Community
  • 1
  • 1
l0b0
  • 55,365
  • 30
  • 138
  • 223
  • I'm pretty sure it *is* an object. Though the properties you are looking for might not be its "own". Have you tried something like `Object.keys(foo)`? – J. Holmes Apr 25 '12 at 08:46
  • 1
    @32bitkid - It's not an object, it's a primitive string value. It will sometimes be temporarily cast to an instance of `String` (if you call a method of `String.prototype` on it for example). l0b0 - Do you want this for a general case (any type) or just for strings? – James Allardice Apr 25 '12 at 08:48
  • @32bitkid - As far as I know, it's just a *string literal* until you use it as object [[ref](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#String_literals)]. I guess this question is all about getting properties from `String`, which is exactly what the linked question talks about. – Álvaro González Apr 25 '12 at 08:50
  • @James_Allardice right on, sometimes my brain goes a little loopy at 4am. Insomnia wins again – J. Holmes Apr 25 '12 at 08:51
  • I'm not sure you can do it. Although, if you enter "String.prototype" in Chrome's console. You get all the methods. – Lee Kowalkowski Apr 25 '12 at 09:00

3 Answers3

3

The methods you want are on the String.prototype, the prototype of all strings, ruler of Valindor.

Object.getOwnPropertyNames('baz'.constructor.prototype)
katspaugh
  • 17,449
  • 11
  • 66
  • 103
1

use can use the below:

$(document).ready(function () {
    var foo = 'bar';
    var div = '';
    var ob = Object.getOwnPropertyNames(foo.constructor.prototype);
    for (var i = 0; i < ob.length; i++) {
        div += ob[i] + "<br/>";
    }
    $(selector).html(div);
});
HGK
  • 386
  • 1
  • 4
  • 13
  • That's a lot of unnecessary boilerplate code for essentially the same solution as @katspaugh. But it's valid, so +1. – l0b0 Apr 25 '12 at 09:22
-2

Use eclipse :)

Or just look here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String

katspaugh
  • 17,449
  • 11
  • 66
  • 103
Pulkit Mittal
  • 5,916
  • 5
  • 21
  • 28