JavaScript & jQuery Tutorials

JS Home Right Arrow JS Reference Right Arrow Object Right Arrow valueOf()

valueOf()  Object  instance method

Description

Returns the primitive value of an object.

  • Automatically invoked when an object is called and a primitive value is expected.
  • The Object.valueOf() method is inherited by all Object descendants.
  • Unless overridden by a custom object valueOf() returns [object Object].

Syntax


Signature Description
anObject.valueOf()Returns the primitive value of an object.

Parameters

None.

Examples

The code below creates an object and displays it.


// Create an object.
anObject = new Object();
alert(anObject.valueOf() + ' anObject is an instance of Object.');

Press the button below to action the above code:

Overriding The Object.valueOf() Method

As you can see when pressing the above button the default for valueOf() on an objectType of Object returns [object Object]. If you want something meaningful returned for your object, you need to override the Object.valueOf() method.

The code below creates a custom object type function and overrides the Object.valueOf() method. We then create and display a string primitive which will use our custom valueOf() method.


// Define a custom object type function.
function HomeOwner(firstName,lastName) {  
  this.firstName=firstName;  
  this.lastName=lastName;  
}  
// Define a custom override function for valueOf().
HomeOwner.prototype.valueOf = function HomeOwnervalueOf() {  
  var primValue = 'Home Owner';  
  return primValue;  
}
// Create and print a HomeOwner primitive.
owner = new HomeOwner('Barney','Magrew');  
alert(owner.valueOf());

Press the button below to action the above code:

Related Tutorials

JavaScript Basic Tutorials - Lesson 7 - Objects



  

go to home page Homepage go to top of page Top