Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I have one constructor function in my code. I have create instance of that constructor. In newly created instance I want to add value or function by using prototype method. But I getting error while doing this. Here is my code fiddle

function a(){
this.d=9
}
a.prototype.one=1;
a.prototype.two=2;


var j= new a();
j.prototype.three=3;

console.log(j)
share|improve this question

marked as duplicate by RobG Jan 8 at 10:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
In newly created instance I want to add value or function by using prototype method. - Why? –  thefourtheye Jan 8 at 10:04
    
You are confused between the default prototype property of Function objects and the internal [[Prototype]] of all Objects used for inheritance that references their constructor's prototype. –  RobG Jan 8 at 10:07
    
@RobG: I think you are right –  amit Jan 8 at 10:14
    
Unfortunately the term "prototype" is used colloquially for both. ECMAScript uses [[Prototype]] for the internal property, but it's awkward to read and write. There must be a better name other than "internal prototype of an instance". –  RobG Jan 8 at 10:16

2 Answers 2

up vote 4 down vote accepted

It should be a prototype of the constructor function, not the object this function produces:

a.prototype.three = 3;

You can't access object's prototype with the prototype key, because prototype reference is not exposed like this. You could do it using __proto__ property though, but this is deprecated. If you need to get a prototype of the object you can make use of Object.getPrototypeOf method:

Object.getPrototypeOf(j) === a.prototype; // true

It's a little confusing here because the word "prototype" sort of means two things. Function prototype is an object that is used when new object is constructed when the function is used like a constructor. Object prototype is a reference to the object which stores inherited methods.

share|improve this answer

J's prototype is undefined, because you cant access it directly, so you cant directly set the property three to the prototype of j.

This is why you are able to add properties to a's prorotype but not to j's prototype, you can try

j.three=3; 

Or a.prototype.three = 3;

fiddle http://jsfiddle.net/s4g2n453/4/

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.