Add value using prototype in function instance

I have one constructor function in my code. I am creating an instance of this constructor. In a newly created instance, I want to add a value or function using the prototype method. But I get an error while doing this. Here is my fiddle code

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


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

console.log(j)
+4
source share
2 answers

It should be the prototype of the constructor function, and not the object created by this function:

a.prototype.three = 3;

You cannot access the prototype of an object using the key prototype, because the link to the prototype does not display like that. You can do this using a __proto__property, but it is deprecated. If you need a prototype of an object, you can use the method Object.getPrototypeOf:

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

, "prototype" . - , , . - , .

+4

J undefined, , J.

a', j',

j.three=3; 

a.prototype.three = 3;

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

+1

Source: https://habr.com/ru/post/1570439/


All Articles