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.