Search code examples
javascriptobjectconstructorprototype-programming

JavaScript: how to access the prototype of a constructor function?


Maybe silly question to the JS gurus and ninjas out there but here goes:

My understanding of the prototype object/property of an object is that it is a blueprint for future instances of an object. Given this, shouldn't a newly created instance of an object be identical to the constructor object that created it?

var x = new Object(); 
console.log(x === Object.prototype); // returns false. why?? 

* UPDATE *

So understanding that this will return false because they are referencing different things, I still find that new Object() and Object.prototype contain a different number of properties. So to refine my question: How do I correctly check the number of properties in a prototype Object; how do I iterate through them?

The reason I got confused by this is that if I create a simple constructor function:

function Circle(){
   this.tail = "yes, has tail";
}

and want to get the number of properties it has, doing something like:

console.log(Object.getOwnPropertyNames(Circle.prototype)); 
// returns "constructor", I expected it to return "tail"

Solution

  • === does not answer the question of whether two things are equivalent, but whether they are references to the same object.

    x and Object.prototype in your example may have the same properties, so you can call them equivalent, but they are two different objects.

    If you do

    x.foo = 3
    

    they are now no longer equivalent, because they were two different objects. You changed one but not the other.

    If

    x === Object.prototype
    

    were true, then

    x.foo === Object.prototype.foo
    

    would be the same regardless of what you assign to x.foo or Object.prototype.foo.

    EDIT:

    function Circle(){ this.tail = "yes, has tail"; }
    
    console.log(Object.getOwnPropertyNames(Circle.prototype)); 
    // returns "constructor", I expected it to return "tail"
    

    There is no tail property on Circle.prototype because you have never done Circle.prototype.tail = ...;. You define tail only on Circle instances via this.tail = ...;.

    I still find that new Object() and Object.prototype contain a different number of properties.

    You are also doing getOwnPropertyNames. The own properties are those that are not inherited from the prototype, so by using that function on x you are explicitly excluding all the properties of Object.prototype.

    The docs for hasOwnProperty explain "own property" pretty well:

    This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.