JavaScript Tutorials - Herong's Tutorial Examples - 2.33, by Herong Yang
Adding and Deleting Object Own Properties
This section provides a quick description of object's own properties. A tutorial example is provided on how to add, update, and delete object's own properties.
When you create a new object from the "Object" constructor, you will get an object with only two default properties:
But you can add more properties to one object at any time using an assignment operation like this:
object_name.property_name = initial_value;
The added property is for this one object only. Other objects will not have this property.
You can also delete properties from one object at any time using a delete operation like this:
delete object_name.property_name;
Here is a tutorial example that shows you how to add a new property, update the property value, retrieve the property value, and delete a property.
<html> <!-- Object_Property.html Copyright (c) 2008 HerongYang.com. All Rights Reserved. --> <head> <title>Object Properties of "Object"</title> </head> <body> <pre> <script type="text/javascript"> // Creating objects of "Object" type var mySite = new Object(); var myBook = new Object(); // Adding a new property to one object only mySite.url = "herongyang.com"; myBook.author = "Herong Yang"; // Updating a property value mySite.url = "www.herongyang.com"; // Showing property values document.writeln('mySite.url: '+mySite.url); document.writeln('myBoot.url: '+myBook.url); document.writeln('mySite.author: '+mySite.author); document.writeln('myBook.author: '+myBook.author); // Is this property for one object only? document.writeln('mySite.hasOwnProperty("url"): ' +mySite.hasOwnProperty("url")); // Deleting a property from one only document.writeln('Deleting mySite.url...'); delete mySite.url; document.writeln('mySite.url: '+mySite.url); </script> </pre> </body> </html>
The result matches my expectation:
mySite.url: www.herongyang.com myBoot.url: undefined mySite.author: undefined myBook.author: Herong Yang mySite.hasOwnProperty("url"): true Deleting mySite.url... mySite.url: undefined
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