Search code examples
javascriptprototype-programming

Prototype property with same name as object property


I have a small snippet of code that assigns a prototype property and an object property using the same name. Accessing this testNumber after creating the object will always show the object property, which I understand as it will first look for the property on the object and then in the objects prototype, and then the protoype's prototype etc.

But my question is, is there any way to directly access the property of the prototype in this case? [Just a note, I don't know when I would actually need to do this in practice, but it's simply something I'd like to find out for my own sanity].

function MyObject1(formalParameter){

    this.testNumber = formalParameter;
}

​MyObject1.prototype.testNumber​ = 55;

var mine = new MyObject1(10);
alert(mine.testNumber);

Solution

  • You could access the prototype through the instance's constructor property:

    alert(mine.constructor.prototype.testNumber);
    

    Won't work if you've done weird things with the prototype without preserving its constructor property, or if you have an instance property called constructor for some reason.