JavaScript Tutorials - Herong's Tutorial Examples - 2.33, by Herong Yang
Adding and Deleting Object Own Methods
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:
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 HerongYang.com. All Rights Reserved. --> <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".
Table of Contents
ECMAScript Language Specification and JavaScript Dialects
Data Types, Variables and Expressions
Creating, Accessing, and Manipulating Arrays
Defining and Calling Functions
Web Browser Supporting JavaScript
Server-Side and Client-Side Web Scripting
Adding and Deleting Object Own Properties
►Adding and Deleting Object Own Methods
Using "this" Keyword to Represent Current Object
Object Literals of the "Object" Type
Objects with Indexed Properties
Differences between "Object" and "Array"
Using "Array" Objects as "Object" Objects
Defining Your Own Object Types
Inheritance of Properties and Methods through the Prototype Object Chain
'jrunscript' - JavaScript Shell Command from JDK
Using Functions as "Function" Objects
Introduction to Built-in Object Types
W3C's Document Object Model (DOM) Specifications