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