Tips and pitfalls for JavaScript objects

Source: Internet
Author: User

3 method methods for creating objects 1

Directly create

var obj = {            name: "Mike",            Age:10        }

Method 2

Create with new

var ob = new Date ();

Method 3

ECMAScript5 has a new method Object.create ()

In fact, the method is to inherit an object

var obj = {            name: "Mike",            age:10        };        var newobj = object.create (obj);        Console.log (Newobj.name);

Some tricks and pitfalls

1

var a = {            name: "Mike",            Name: "John"        }        Console.log (a["name"]);
Accidentally writing a property name as a result is John, which means that when a property name is encountered. According to the last occurrence, note that when you start using strict, you will get an error.

2

var a = {};        a.x = 1;        var p = object.create (a);        P.Y = 2;        Console.log (p.x);
When you access the object's properties, he will continue to look up along the prototype chain,

3

var a = {};        a.x = 1;        var p = object.create (a);        P.Y = 2;        Console.log ("X" in P); True

There is no such attribute in an object if it is inherited.

4

var a = {};        a.x = 1;        var p = object.create (a);        P.Y = 2;        Console.log ("X" in P); True        Console.log (P.hasownproperty ("X"));//false
Check your own properties

5

var a = {            x:1,            get Getx () {return this.x;},            set Setx (ARG) {                return this.x = arg;            }        }        Console.log (a.x);        a.x = +;        Console.log (a.x);

Property can be set read-only, read/s Write

6

var a = {            x:1,            get Getx () {return this.x;},            set Setx (ARG) {                return this.x = arg;            }        }        Object.freeze (a);        a.x = +;        Console.log (a.x); 1

Freezing an object to ensure that the object's closeness is not compromised


Tips and pitfalls for JavaScript objects

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.