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!

ankush981
  • 5,159
  • 8
  • 51
  • 96
  • 1
    Maybe the following answer can help you: http://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 – HMR Nov 18 '14 at 05:11
  • @HMR Yes, that adds to the clarity. I'm still very far from understanding the complete picture, but every bit helps. ^.^ – ankush981 Nov 18 '14 at 05:34
  • Objects inherit via their internal `[[Prototype]]`, which is a reference to the prototype of their constructor at the time they were instantiated. – RobG Nov 18 '14 at 06:17

2 Answers2

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__;
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Does not make complete sense because I'm still struggling with the intricacies of JavaScript. Will accept this as answer, though. Thanks! :) – ankush981 Nov 18 '14 at 04:53
  • There is also `obj.constructor.prototype` but it's not reliable. – RobG Nov 18 '14 at 06:24
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.

Scott Rippey
  • 15,614
  • 5
  • 70
  • 85