Categories:

JavaScript Kit > JavaScript Reference > Here

Object object

Last updated: January 7th, 2013

You can define your own objects in JavaScript, with custom properties and methods.

Constructor:

var myobject=new Object()

var myobject={ } //object literal. Supported in JavaScript 1.2

Related Tutorials

Properties

Properties Description
constructor Specifies the function that's the constructor for the object.

Methods

Methods Description
__defineGetter__

JavaScript 1.5 feature, supported in FF, Chrome, Safari 3+, but not IE10

Method for getting the value of a property of a JavaScript object or function. In the past coders have defined their own getter and setter functions within an object to conveniently access and change data within an object- now you can do this natively and using more streamlined code.

The following defines two getter functions inside another to access the "private" properties of the later:

function getarea(width, height){
 var w = width //private prop
 var h = height //private prop

 this.__defineGetter__("w", function(){
  return w
 })

 this.__defineGetter__("h", function(){
  return h
 })

}

var house = new getarea(200, 400)
alert(house.w + " by " + house.h) // alerts "200 by 400"

When defining a getter method inside an object literal, the syntax is different, and should be in the form get functionname(){...}:

var myspace = {
 x: null,
 y: null,

 get xplusy(){
  return this.x + this.y
 },


 init:function(xval, yval){
  this.x = xval
  this.y = yval
 }
}

myspace.init(200, 500)

alert(myspace.xplusy) // alerts 700

__defineSetter__

JavaScript 1.5 feature, supported in FF, Chrome, Safari 3+, but not IE10

Method for setting the value of a property of a JavaScript object or function. Lets extend the getarea() function above with a setter method for the private variable "w":

function getarea(width, height){
 var w = width //private prop
 var h = height //private prop

 this.__defineGetter__("w", function(){
  return w
 })

 this.__defineGetter__("h", function(){
  return h
 })

 this.__defineSetter__("w", function(val){
  w = val
 })


}

var house = new getarea(200, 400)
house.w = 300 // call setter method "w" and pass 300 into its parameter
alert(house.w + " by " + house.h) // alerts "300 by 400"

As you can see, when defining a setter method, the syntax is almost identical to a getter method, with the exception that its function accepts a parameter whose value is assigned to it by you when calling it.

Getter/ Setter methods can also be defined on the prototype property of objects. The following defines a setter method on the Array object to modify the order of the array when set:

Array.prototype.__defineSetter__("sorttype", function(x){
 if (x == "alpha"){
  this.sort()
 }
 else{ // otherwise, assume sort numerically and ascending
  this.sort(function(a,b){return a -b})
 }
})

var arr = [23, 245, 54]
arr.sorttype = "alpha" // probing arr would return [23, 245, 54]
arr.sorttype = "numeric" // probing arr would return [23, 54, 245]

When defining a setter method inside an object literal, the syntax is different, and should be in the form set functionname(){...}:

var myobject = {
 a: 5,
 b: 10,
 get ab(){return this.a + this.b},
 set aplus(c){this.a = this.a + c}
}

myobject.aplus = 4 // a is now 9
myobject.ab // returns 19 (9 + 10)

hasOwnProperty(prop) Returns true if an object has a property with the name as indicated by the parameter prop. Returns false if the property doesn't exist or is inherited from the prototype chain versus a direct property of the object.

var dog=new Object()
dog.age=5
dog.hasOwnProperty("age") //returns true
dog.hasOwnProperty("favoritefood") //returns false, property doesn't exist
dog.hasOwnProperty("toString") //returns false, as toString property is inherited

isPrototypeOf(obj) Returns true if one object is the prototype of another . Use this method to detect the class of an object (obj).

Example 1:

var fruits=["apple", "grapes"]
Array.prototype.isPrototypeOf(fruits) //returns true, "fruits" in an array
Function.prototype.isPrototypeOf(fruits.slice) //returns true, fruits.slice() is a function

Example 2:

function Car(){
//Car class here
}

function Toyota(){
//Toyota object here
}

Toyota.prototype=new Car() //inherit from Car class
var Prius=new Toyota //instance of Toyota object
Car.prototype.isPrototypeOf(Prius) //returns true, Prius is an instance of Toyota which inherits from Class Car

Object.keys(obj)

Supported in FF4+, IE9+, Chrome5+, and Safari 5+

Returns an array of all the enumerable property names of an object (though not those in its prototype chain). The order of the names is the same as that returned by using a for-in loop to retrieve the property names. For example:

var box={width:100, height:35, length:40}, boxvolumn=1
var keys=Object.keys(box) //returns ["width", "length", "height"]

for (var i=0; i<keys.length; i++){
 boxvolumn*=box[keys[i]] //multiple all property values of object
}
alert(boxvolumn) //alerts 140000

The difference between using Object.keys() to return an object's properties and using a for-in loop is that the later also returns any enumerable properties inherited from the object's prototype chain, not just those directly attached to the object.

To get all enumerable and non enumerable properties of an object, use getOwnPropertyNames(obj) instead. All user defined properties of an object are enumerable, while in general, built in properties/methods are not.

Note: See Looping through an object's properties as well.

Object.getOwnPropertyNames(obj)

Supported in FF4+, IE9+, Chrome5+, and Safari 5+

Similar to keys(obj) above but also returns the non enumerable properties of an object. All user defined properties of an object are enumerable, while in general, built in properties/methods are not.

You can use getOwnPropertyNames(obj) to get all the properties of built in objects easily:

var stringprops=Object.getOwnPropertyNames(String)

//returns ["prototype", "quote", "substring", "toLowerCase", "toUpperCase", "charAt", "charCodeAt", "indexOf", "lastIndexOf", "trim", "trimLeft", "trimRight", "toLocaleLowerCase", "toLocaleUpperCase", "localeCompare", "match", "search", "replace", "split", "substr", "concat", "slice", "fromCharCode", "length", "arity", "name", "arguments", "caller"]

var stringprops=Object.getOwnPropertyNames(Array)

//returns ["prototype", "join", "reverse", "sort", "push", "pop", "shift", "unshift", "splice", "concat", "slice", "indexOf", "lastIndexOf", "forEach", "map", "reduce", "reduceRight", "filter", "some", "every", "isArray", "name", "length", "arity", "arguments", "caller"]

Note: See Looping through an object's properties as well.

propertyIsEnumerable(prop) Returns true if the entered property name of this object is enumerable using for-in Returns false if either property doesn't exist, or if the object inherited the property from the prototype object. All user defined properties to an object are enumerable, while in general, built in properties/methods are not.

var mycar=new Object()
mycar.size="mid"

mycar.propertyIsEnumerable("size") //returns true for local user defined property
mycar.propertyIsEnumerable("toString") //returns false for prebuilt property
mycar.propertyIsEnumerable("cost") //returns false for non existent local property

toString() A method that's typically called implicitly by JavaScript whenever you call an object within the context in which a string value is expected, such as alerting an object: alert(mycar). By default it returns the object in the string representation [object Type].

A common task for programmers to do is to override this method with something more robust, especially for custom objects. the default returned value is less than descriptive of the object. For example:

function records(){
 this.records=[]
 for (var i=0; i<arguments.length; i++)
  this.records.push(arguments[i])
}

records.prototype.toString=function(){
 return "All records: "+this.records.join(" | ")
}

var myrecords=new records("George", "Edward", "Sue")
alert(myrecords.toString()) //alerts "George | Edward | Sue"

 

valueOf() A method that's typically called implicitly by JavaScript whenever you call an object within the context in which a primitive value is expected. Rarely if ever called explicitly.

Looping through object properties

There are a few ways to loop through an object's properties, depending on your needs.

For-in Loop

The for-in loop, supported by all browsers since the dawn of time, can be used to loop through both an object's enumerable properties, plus any enumerable properties inherited by the object's prototype chain.

var userprofile={name:'George', age:30, sex:'male', getage:function(){return this.age}}, props=[]
for (var p in userprofile){ //loop thru properties of object
 props.push(p) //props will contain ["name", "age", "sex", "getage"]
}

Or:

function circle(r){
 this.radius=(typeof r!="undefined")? r : this.radius //get radius of circle instance
 this.area=Math.pow(this.radius,2) * 3.14
}

circle.prototype={
 radius: 2, //default radius of circle

 getparameter:function(){
  return 2 * 3.14 * this.r
 }
}

var circle1=new circle(), props=[]

for (var p in circle1){ //loop thru properties of object
props.push(p) //props will contain ["radius", "area", "getparameter"]
}

Object.keys(object)

Object.keys(object), supported in FF4+, IE9+, Chrome5+, and Safari 5+, lets you easily get the enumerable properties of an object, not including any inherited from the prototype chain. It returns the data as an array:

var userprofile={name:'George', age:30, sex:'male', getage:function(){return this.age}}
var props=Object.keys(userprofile) //props will contain ["name", "age", "sex", "getage"]

Cross browser version of Object.keys()

For browsers that don't support Object.keys(), we can bridge that gap by implementing a cross browser version of Object.keys() on our own that take advantage of different features of JavaScript depending on which ones the browser supports:

if (typeof Object.keys=="undefined"){
 Object.keys=function(obj){
  var props=[]
  for (var p in obj){
   if (obj.propertyIsEnumerable(p))
    props.push(p)
  }
  return props
 }
}

Object.getOwnPropertyNames(object)

Finally, there's Object.getownProperty(object), which is also supported in FF4+, IE9+, Chrome5+, and Safari 5+. Use this method to easily loop through all enumerable PLUS non enumerable properties of an object (those found in the prototype chain NOT included), which comes in handy for built in objects' properties, such as String, Math, or Array. The following loops through the Math object of JavaScript and calls on all of the trigonometry related methods of the object on a number:

var trigmethods=Object.getOwnPropertyNames(Math).filter(function(element, index, array){
 return (/(acos)|(asin)|(atan)|(atan2)|(cos)|(sin)|(tan)/i.test(element))
})

for (var i=0; i<trigmethods.length; i++){ //loop through all trig related methods of Math
 alert(Math[trigmethods[i]](2.5)) //call Math.trigfunction(2.5)
}

Reference List

Right column

CopyRight (c) 2018 JavaScript Kit. NO PART may be reproduced without author's permission. Contact Info