Best practice for determining objects type in Javascript -
if have instance of object in javascript, seems can difficult find actual type, ie
var point2d = function point2d(x, y) { return { x: x, y: y } } var p = new point2d(1,1); typeof p // yields 'object' not 'point2d'
one way around found make object own prototype, , can gets name calling prototype.constructor.name,
var point2d = function point2d(x, y) { return { x: x, y: y, prototype: } } new point2d(1,1).prototype.constructor.name // yields 'point2d'
would ok way of doing (what pros/cons?) or there better practice missing out on?
thanks.
first need fix how building class, since tripping in js pitfalls , doing weird stuff:
function point2d(x, y){ //our constructor/initialization function //when run, 'this object have //point2d.prototype prototype this.x = x; this.y = y; //don't return value here! doing overrides //the default "return this" want. } //you can put things in point2d prototype in order have them //be shared point2d objects. want methods shared. point2d.prototype.getx = function(){ return this.x; }; //note there nothing magical "prototype" property. //it `new` syntax expects prototype use be. //the actual magic property __proto__ (don't depend on though // __proto__ browser specific , unsafe/evil) //we can create points! var p = new point2d(17.0, 42.0); p.getx();
now can tackle part getting type names. better practice missing on not inspecting type in first place. oo perspective shouldn't matter how object implemented (ts class) how behaves , interface (exposed methods , properties). also, javascript perspective, type names second-class hack don't fit prototypical oo scheme used.
since there many reasons trying inspect type name in first place, there many different "best" solutions. think of:
if case "does object implement particular point interface" can feature-inspection directly:
function ispoint(p){ //check if p has methods expect point have: //(note functions truthy in boolean context) return (p.getx && p.gety); }
if use type names dispatching consider using method instead. natural oo way.
function speak(obj){ //fake pseudo-syntax: if(obj of type cat){ console.log("meow"); } if(obj of type dog){ console.log("woof"); } }
becomes
cat.prototype.speak = function(){ console.log("meow"); }; dog.prototype.speak = function(){ console.log("woof"); };
if really need sort of tag, can explicitely make one, pointed of other answers already:
point2d.prototype.pointtype = "2d";
the advantages here can have more 1 class have same "type" if need , don't have worry of tricky
instanceof
ortypeof
corner cases.
Comments
Post a Comment