This section provides a quick description of object's own methods. A tutorial example is provided on how to add, call, and delete object's own methods.
When you create a new object from the "Object" constructor, you will get an object with only some default methods:
"toString()" - This default method outputs "[object Object]". It needs to be placed with a real one.
"valueOf()" - This default method outputs "[object Object]". It needs to be placed with a real one.
But you can add more methods to one object at any time using an assignment operation like this:
object_name.method_name = function_name;
The added method is for this one object only. Other objects will not have this method.
Calling a method on an object is the same as calling the assigned function as shown below:
object_name.method_name(param1, param2, ...);
You can also delete methods from one object at any time using a delete operation like this:
delete object_name.method_name;
Here is a tutorial example that shows you how to add a new method, call a method, and delete a method.
<html>
<!-- Object_Method.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Object Methods of "Object"</title>
</head>
<body>
<pre>
<script type="text/javascript">
// My function to say hello
function sayHello(name) {
window.alert("Hello "+name);
}
// Preparing two objects of "Object" type
var mySite = new Object();
var myBook = new Object();
mySite.url = "herongyang.com";
myBook.author = "Herong Yang";
// Adding a method to one object only
myBook.greet = sayHello;
// Calling the method on "myBook"
myBook.greet(myBook.author);
// Calling the method on "mySite" - will not work
// mySite.greet(myBook.author);
// Deleting the method on "myBook"
delete myBook.greet;
// Calling the method on the object - will not work
// myBook.greet(myBook.author);
</script>
</pre>
</body>
</html>
If you run this JavaScript page, you will get alert box on the screen saying: "Hello Herong Yang".