Techniques and traps for Javascript objects

Source: Internet
Author: User

Techniques and traps for Javascript objects
Method 1

Create directly

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, this method inherits an object.

var obj = {            name: "mike",            age: 10        };        var newobj = Object.create(obj);        console.log(newobj.name);

Tips and traps

1

var a = {            name: "mike",            name: "john"        }        console.log(a["name"]);
Accidentally writing the attribute name as the same result is john. That is to say, when the attribute name is the same, an error will be reported when the use strict command is started.

2

var a = {};        a.x = 1;        var p = Object.create(a);        p.y = 2;        console.log(p.x);
When the properties of the object you access are not available, the object will be searched 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

Is there a property in an object that 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 attributes

5

var a = {            x:1,            get getx() {return this.x;},            set setx(arg) {                return this.x = arg;            }        }        console.log(a.x);        a.x = 100;        console.log(a.x);

Attribute can be set to 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 = 100;        console.log(a.x); //1

Freezing an object ensures that the object's closeness is not damaged.


Related Article

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.