class - How to get rid of instanseof in javascript -


i have class, has 2 methods: get(), set().

function a() {     var value = '';     this.get = function () {         return value;     };     this.set = function (v) {         value = v;     }; } 

and have function f():

/**  *  * @param { string | number } b  */ function f(b){     var value;     if(b instanceof a){         value = b.get();     }else{         value = b;     } } 

i create object:

var test = new a(); test.set('hello'); f(test); //hello f(10); //10 

the instanceof operator tests whether object has in prototype chain prototype property of constructor. heard bad practice use operator. question is: imposible rid of instanceof operator code? maybe should use force type conversion or use getter, setter?

<--update-->>

i found simple solution, coerce b.get boolean type , check it. works, maybe has incidental effect.

 value = (!!b.get) ? b.get(): b; 

<--update 2-->>

another way: value = (b.constructor = a) ? b.get(): b;

it's not instanceof operator problem, it's you're using for. function expecting values of 2 different types: either instance of a needs handled way or else can used is.

the problem a) why function allowing 2 different types begin , couldn't harmonise 1 type, , b) if it's accepting "anything" or "a", why a , not more general?

assuming cannot reasonably change point a), can @ least make b) better:

if (typeof b.get == 'function') {     value = b.get(); } 

you've made function little more flexible , adaptable future change testing actual thing you're interested in: get method. b instanceof a sort of irrelevant task @ hand , may limit in future.


Comments