Romantic Electron
Romantic Electron

Reputation: 779

Object.prototype not working but Object.__proto__ working why?What to do to make my code working in all browsers?

I read somewhere that Object.__proto__ and Object.prototype point to the same thing and the Object.prototype is the standard way,but last night I was trying to inherit a class with Object.prototype but it did not work then I tried to figure out whether both the Object.__proto__ and Object.prototype point to the same thing or not.To my surprise

    alert(Object.__proto__===Object.prototype);

displayed false in an alertbox So to figure out which one works I wrote the following code

    function Cx(){
    this.objName="i m X";
    this.prototype={ };
    this.prototype.getMyName=function (){
alert(this.objName);
       }
    this.__proto__={ };
    this.__proto__.hMyName=function(){
alert("I am hMyName");
      }
    }
    function InheritCx(){
//var y=new Cx();
this.objName="I am InheritCx";
this.__proto__=new Cx();

    }
    y= new InheritCx();
    y.hMyName();//displayes "I am hMyName" in alertbox when using chrome or mozilla
    y.getMyName();//displays an error in chrome and mozilla

What's the difference between the two and why doesn't the standard code work? Furthermore I am interested in knowing what can I do to make prototypal inheritance work in most browsers (IE 6-8,9,10,chrome,firefox,mozilla,opera and webkit)?

Upvotes: 2

Views: 824

Answers (1)

user1106925
user1106925

Reputation:

The .__proto__ is a non-standard way of getting the next object that a given object inherits from. Reading the property is equivalent to the standard Object.getPrototypeOf().

var o = {}; // new object

console.log(o.__proto__ === Object.getPrototypeOf(o)); // true

The .prototype property of a function is the object that new objects will inherit from that were created when invoking that function as a constructor (using new).

So if we take a function, invoke it as a constructor by using new, then take the new object and ask for its __proto__, it will be the same object as that found on the .prototype property of the constructor.

function Ctor() {
    // our constructor function
}

var o = new Ctor();

console.log(o.__proto__ === Ctor.prototype); // true

Upvotes: 3

Related Questions