node.js inheritance prefer child constructor properties -



node.js inheritance prefer child constructor properties -

var util = require('util'); function entity(){ //this.x == 10 @ point this.x = 0; this.y = 0; this.globalinit(); } entity.prototyp.globalinit = function(){ console.log("this.x ", x); }; function actor(){ this.x = 10; this.y = 10; actor.super_.apply(this, arguments); } util.inherits(entity, actor); var = new actor(); //outputs -> this.x 0

i have these 2 constructors. want have properties defined in kid constructor final properties. move actor.super_.apply top of constructor there initialization logic ( globalinit ) want maintain @ end of parent constructor

i can see 2 solutions this. first, parent constructor take in parameters x , y, , default them parent class values.

function entity(x, y){ this.x = typeof x === 'undefined' ? 0 : x; this.y = typeof y === 'undefined' ? 0 : y; this.globalinit(); } function actor(){ actor.super_.call(this, 10, 10); }

this method work best if there not many properties , it's not problem allow them passed in. breaks downwards if initialization complex.

the sec method bit more general in cases have complicated initialization. essentially, want introduce mill methods produce instances of objects, can perform arbitrarily complex initialization. instance,

function entity(){} function actor(){} function createentity(){ var e = new entity(); e.x = 0; e.y = 0; e.globalinit(); homecoming e; } function createactor(){ var = new actor(); a.x = 10; a.y = 10; a.globalinit(); homecoming a; }

clearly can refactored farther dry code, perchance variant of first solution.

using mill methods rather straight invoking constructor adds value in other ways well. decouples 2 modules somewhat, consumer of these entities , actors doesn't need know how build them. allows have multiple different "constructor" signatures without painful argument analysis.

node.js inheritance prototypal-inheritance

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -