简体   繁体   中英

why I am not able to call function while defining in prototype?

I am making an example of inheritance. I want to access all properties of abc and pqr so I used Object.create . However I am not able to get the value of r while calling the getr() function. What am I doing wrong?

 function abc() { this.a = 3; } abc.prototype.getA = function() { return this.a } function pqr() { abc.call(this); this.r = 3; } pqr.prototype.getr = function() { return this.r } pqr.prototype = Object.create(abc.prototype); var n = new pqr(); console.log(n.getr());

The issue is because you overwrite the pqr.prototype after you create getr() . Swap the order of those statements:

 function abc() { this.a = 3; } abc.prototype.getA = function() { return this.a; } function pqr() { abc.call(this); this.r = 3; } pqr.prototype = Object.create(abc.prototype); pqr.prototype.getr = function() { return this.r; } var n = new pqr(); console.log(n.getr());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM