3

I'm confused why var obj = {}; or var obj = new Object(); then obj.getOwnPropertySymbols is undefined??


example 1


example 2

neaumusic
  • 10,027
  • 9
  • 55
  • 83

3 Answers3

3

Object itself has some methods defined, such as Object.keys. These aren't defined on Object.prototype, so they're not available on object instances.

Bo Borgerson
  • 1,386
  • 10
  • 20
  • dang, yea i don't know how this wasn't obvious to me, very strange to not put helper functions on the prototype – neaumusic Jun 18 '16 at 03:23
  • Nah it's not. If that happened you'd be unable to define a method called `keys()` for example, it would be a nightmare for backwards compatibility – Dan Oct 21 '17 at 19:46
3

Constructors have two separate kinds of methods:

  • Prototypical methods

    Defined as properties of Constructor.prototype, the are only available on instances.

  • Static methods

    Defined as properties of Constructor itself, the are only available on the constructor.

ES6 classe make it clear

class Constructor {
  static foo() { return 123; }
  bar() { return 456; }
}
Constructor.foo(); // 123
Constructor.bar;   // undefined
new Constructor().foo; // undefined
new Constructor().bar; // 456

Your case is special, however: the static methods of the Object constructor seem to include the prototypical methods. But that's because Object inherits from Object.prototype.

The prototypical chains are like

  • Object instance

    instance -> Object.prototype -> null
    
  • Object constructor

    Object -> Function.prototype -> Object.prototype -> null
    
Oriol
  • 274,082
  • 63
  • 437
  • 513
1

Technically, Object (the constructor) is not of the type object, it's a class/function depending on what term you want to using with JS. Because it's a class, it has methods on it that are not used in instances of that object. IE: they're not on the returned objects prototype.

In your Chrome console, try this:

var obj = {};
typeof obj; // "object"
typeof Object; // "function"

Look into the way class prototyping works in JS when you get a chance.

To clarify a bit, when you run new Object() it returns something with the type of object that has the necessary methods on it.

I think this is a good reference of what I'm talking about: JavaScript - The Good Parts: Function prototypes vs Object prototypes

You can see the same behavior with Number and String. The types of both are actually function, but once they're created, you get one of the type of number or string, each with their relevant prototype methods.

The bottom line is the constructor is not the same as the returned value.

Community
  • 1
  • 1
Jacques ジャック
  • 3,682
  • 2
  • 20
  • 43