9

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)
Jitender
  • 7,593
  • 30
  • 104
  • 210
  • `In newly created instance I want to add value or function by using prototype method.` - Why? – thefourtheye Jan 08 '15 at 10:04
  • You are confused between the default *prototype* property of Function objects and the internal [`[[Prototype]]`](http://ecma-international.org/ecma-262/5.1/#sec-8.6.2) of all Objects used for inheritance that references their constructor's [*prototype*](http://ecma-international.org/ecma-262/5.1/#sec-15.3.5.2). – RobG Jan 08 '15 at 10:07
  • @RobG: I think you are right – Jitender Jan 08 '15 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 08 '15 at 10:16

2 Answers2

4

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
1

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/

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88