Javascript Single-User Inheritance

I would like to keep one parent class. all clild classes that inherit from the parent class will be able to share the same parent class object. How can this be achieved?

var ParentClass = function(){ this.a = null; } ParentClass.prototype.setA = function(inp){ this.a = inp; } ParentClass.prototype.getA = function(){ console.log("get a "+this.a); } // Clild Class var ClassB = function(){} ClassB.prototype = Object.create(ParentClass.prototype); var b = new ClassB(); b.setA(10); b.getA(); //it will return 10 //Another clild Class var ClassC = function(){} ClassC.prototype = Object.create(ParentClass.prototype); var c = new ClassC(); c.getA(); //I want 10 here. 

I understand that for the second clild class, the parent class instantiates again, so I cannot access the old object. How can I achieve this singleton inheritance in Javascript? Any idea?

+4
source share
2 answers

Put such static values ​​in another place. this is the current instance, not the one where you want to create a new property. Possible options:

  • ParentClass.prototype (as @bfavaretto shown), which will result in all instances inheriting and having the ability to overwrite it
  • variable with scope (basically implementing the expander module template):

     (function() { var a; ParentClass.prototype.setA = function(inp){ a = inp; }; ParentClass.prototype.getA = function(){ console.log("get a "+a); return a; }; }()); 
  • the ParentClass function object ParentClass :

     ParentClass.prototype.setA = function(inp){ ParentClass.a = inp; }; ParentClass.prototype.getA = function(){ console.log("get a "+ParentClass.a); return ParentClass.a; }; 
+2
source

When you call getA from any instance, the value of this inside it will point to the instance itself. You can achieve what you are looking for by changing the installation code:

 ParentClass.prototype.setA = function(inp){ ParentClass.prototype.a = inp; } 

Note that calling getA from the getA instance returns null , and the constructor defines its own property a , which obscures it with the prototype.

+1
source

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


All Articles