Common operations for JS objects (ADD, delete, Judge properties)

Source: Internet
Author: User
Tags hasownproperty

Create an empty object user:
var user=new Object ();

1. Adding attributes

1.1. General Add attribute (property name known)
At this point the user object does not have any properties and methods, and obviously has no purpose. However, you can add properties and methods dynamically for it, for example:
User.name= "Jack";
user.age=21;
user.sex= "Male";

user["height"] = 158; Use square brackets ([]) syntax

User.alert=function () {//Add method
Alert ("My name is:" +this.name);
}

1.2. Dynamic Add Property (property name unknown)

var p = "Name";

User[p] = "Jack"; Equivalent to User.Name = "Jack"

2. modifying properties
The process of modifying a property is to replace the old property with a new one, for example:
User.height = 160;

3. Delete Property

Delete user.name;//deleting properties

Console.log (user.name);//undefined

4. Determine if an object contains a property

4.1 Method One: In method

alert( ‘name‘ in user );  // --> true alert( ‘weight‘ in user );  // --> false alert( ‘toString‘ in user );  // --> true

NT: You can see that the return true is detected either by name or by ToString on the prototype chain.

4.2 Method One: hasOwnProperty method

user.hasOwnProperty( ‘name‘ );  // --> true user.hasOwnProperty( ‘toString‘ );  // --> false

NT: The inherited property on the prototype chain cannot be detected by hasOwnProperty and returns false. It is important to note that although in can detect the properties of the prototype chain, the for in is usually not possible.

More knowledge of for in is described in the for-in flaw.

Common operations for JS objects (ADD, delete, Judge properties)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.