oop - Can you set a object type to custom name instead of function in Javascript -
i wondering if following situation possible. trying write object factory, construct different types of objects. trying figure out, if possible in java script set type other function or object? similar in c# how class instance of car typeof car, though base type object. explaining clearly. best way explain it, demonstrated below:
var object = function(){ switch(id){ case 1: $_objinstance = new car(); break; case 2: $_objinstance = new animal(); break; return $_objinstance; } function car(){ this.name = "gm"; } document.write(object instanceof car); or typof( object) == car //is possible?
thanks in advance! happy coding:)
what trying figure out, if possible in java script set type other function or object?
no, can't. however:
javascript have
instanceof
operator can use test instance see if it's have been constructed given constructor:if (obj instanceof car) { // ... }
function#name
remains unreliable in wild (in javascript engines don't set reliably yet), set explicitly on constructor functions:car.name = "car";
...and use
obj.constructor.name
find name of constructor. relies on object inheritingconstructor
property correctly, if don't mess default object on function'sprototype
property.
several years wrote blog post typeof
, instanceof
, object.prototype.tostring
, , various other ways can use determine is, although left off option of setting own name.
here's example of using .constructor.name
:
function car() { } car.name = "car"; function animal() { } animal.name = "animal"; snippet.log("randomly constructing 10 cars or animals:"); (var n = 0; n < 10; ++n) { var x = math.random() < 0.5 ? new car() : new animal(); snippet.log("we got: " + x.constructor.name); }
<!-- script provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
when said above
that relies on object inheriting
constructor
property correctly, if don't mess default object on function'sprototype
property.
let me give example messes up, know keep eye out for. routinely see people doing this:
// problematic: wipes out `constructor` property function car() { } car.prototype = { drive: function() { } // ... };
that is, rather augmenting object car.prototype
got originally, replace it. prefer augment (e.g., don't replace whole object, add properties it), various reasons, if do replace can make sure give new 1 correct constructor
:
// keeps `constructor` correct function car() { } car.prototype = { constructor: car, drive: function() { } // ... };
Comments
Post a Comment