JS Objects


Objects are groups of data and methods, javascript has built in Objects such like Date, String, Math, Array etc. In fact, everything is an object in javascript, e.g. a number, a letter, a function etc.

constructor property returns the Object constructing prototype:

var x = 4;
var x = arr.constructor;
//x = "function Number() {[native code]}"


prototype property adds property or method to an Object. Following example add a method sqrt() to Object Array, which can get the square root of all array elements:

Array.prototype.sqrt = function()
{
for (var i=0; i<this.length;i++)
{
this[i] = Math.sqrt(this[i]);
}
}
var arr = [4,16,9];
arr.sqrt(); //arr now is [2,4,3]


Create javascript Object directly using ":" or new keyword:

var city = {
name:"Miami", country:"USA", region:"America"
};
var city = new Object();
city.name = "New York";
city.country = "USA";
city.region = "America";


Object constructor:

function city(name,country,region)
{
this.name = name;
this.country = country;
this.region = region;
function iscapital()
{
if (this.name == "Washington DC") return true;
return false;
}
}


Create an Object Instance:

var newyork = new city("New York","USA","America");
alert(newyork.iscapital()); //false


endmemo.com © 2024  | Terms of Use | Privacy | Home