1

(I'm new to JavaScript) If all objects inherit their properties from a prototype, and if the default object is Object, why does the following script return undefined in both cases (I was expecting 'Object')?

obj1 = {}; //empty object
obj2 = new Object();
console.log(obj1.prototype);
console.log(obj2.prototype);

Pardon me if it's a silly question!

3
  • 1
    Maybe the following answer can help you: stackoverflow.com/a/16063711/1641941 As the answer indicates; prototype is a property of instances of Function and is used as the first item in the prototype chain of instances created with that function. var c = new Object(); the Object instances called c would use Object.prototype as it's first item in it's prototype chain. But since c is not an instance of Function it does not have a prototype member. If you do var q = new Function() then q would have a prototype member Commented Nov 18, 2014 at 5:11
  • @HMR Yes, that adds to the clarity. I'm still very far from understanding the complete picture, but every bit helps. ^.^ Commented Nov 18, 2014 at 5:34
  • Objects inherit via their internal [[Prototype]], which is a reference to the prototype of their constructor at the time they were instantiated. Commented Nov 18, 2014 at 6:17

2 Answers 2

4

.prototype is not a property of a live object and thus it doesn't exist so it reports undefined. The .prototype property is on the constructor which in this case is Object.prototype. For a given object in a modern browser, you can get the active prototype with this:

var obj1 = {}; 
var p = Object.getPrototypeOf(obj1);

A non-standard and now deprecated way to get the prototype is:

var obj1 = {}; 
var p = obj1.__proto__;
Sign up to request clarification or add additional context in comments.

2 Comments

Does not make complete sense because I'm still struggling with the intricacies of JavaScript. Will accept this as answer, though. Thanks! :)
There is also obj.constructor.prototype but it's not reliable.
1

In JavaScript's prototypal inheritance, you have constructors and instances.
The constructors, such as Object, is where you find the .prototype chain.
But on the instances, the prototype chain is not really accessible.

1 Comment

@RobG Thanks, I removed the comment about the __proto__ property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.