Javascript Object

Object Javascript


var myCat = {
  "name": "hachii",
  "legs": 4,
 "color": "white",
};

myCat.speck = "meo";
delete myCat.color;


Lookup with Object

val ="alpha";

 var arrData = {

    "alpha":"Adams",

    "bravo": "Boston",
    "charlie": "Chicago",
    "delta":  "Denver",
    "echo":"Easy",
    "foxtrot": "Frank"
  };
  
  result = arrData[val];

Testing Object for Properties

- .hasOwnProperty(propname)

 var arrData = {
    "alpha":"Adams",
    "bravo": "Boston",
    "charlie": "Chicago",
    "delta":  "Denver",
    "echo":"Easy",
    "foxtrot": "Frank"
  };

a = "alpha";
b= "beta";

arrData.hasOwnProperty(a); // true
arrData.hasOwnProperty(b); // false


Example of construction Function


var Car = function() {
  this.wheels = 4;
  this.engines = 1;
  this.seats = 5;
};


Create Instance of Object with construction Function

var myCar = new Car();

// now 
myCar =  {
 wheels : 4,
 engines : 1,
 seats : 5
};

We can use this:
myCar.wheels = 4;

myCar.name = "Ferrari";  // we can create its attribute


Parameter to Constructor Function

var Car = function(wheel,engin, seat) {
  this.wheels = wheel;
  this.engines = engin;
  this.seats = seat;
};

var myCar = new(4,8,2);
// now 
myCar =  {
 wheels : 4,
 engines : 8,
 seats : 2
};

Object Properties Private vs Public


var Bike = function() {

  // gear is private and only assisible inside
  var gear;

  // these are public methods
  this.setGear = function(change) {
    gear = change;
  };

  this.getGear = function() {
    return gear;
  };

};

Share this

Related Posts

Previous
Next Post »