Heartbit
Heartbit

Reputation: 1836

What is the best way to check for given options?

I have an object constructor that take an object as it's argument. I need to check for an specific property in that objects that inherit from this object. something like this:

function Direction(option) {
  this.color = 'red' || option.red;
  this.step = 2;
}

Direction.prototype.getColor = function(){
  return this.color;
}

Direction.prototype.getStep = function() {
  return this.step;
}


//Given options are:
var opt = {
  rStep : 9,
  lStep : 3,
  rColor : 'green',
  lColor : 'yellow'
}

var childmaker = function(op){
  
  //here I used some if statement for checking needed properties
  //r_opt
  //l_opt
  
  var right = new Direction(r_opt);
  var left = new Direction(l_pt);

}

childmaked(opt);

if the options become larger how I can check for?

Upvotes: 1

Views: 40

Answers (2)

Yash Gupta
Yash Gupta

Reputation: 588

You can have an array of option/attribute key suffixes you want to check for. Call it suffixes

Then you can loop over them for(var suffix in suffixes){} and check if it is defined on the passed object using typeof(op['r'+suffix])=='undefined'

Upvotes: 1

leguano
leguano

Reputation: 171

You can check a property of an object with

if(myObject.hasOwnProperty('propName') && myObject.propName === 'someValue'){
//do something
}

Upvotes: 1

Related Questions