The first three methods are essentially the same, with the following memory:
JS the first way to create an object (create a new instance of an object):
var person = new Object ();
Person.name = Zhangsan;
Person.age = 18;
Person.sayname = function () {
alert (this.name);
};
JS creates the second way of the object (the literal form creates a new instance of an object):
Note that the attribute is written as a colon between the values, and multiple attributes are separated by commas.
var person = {
Name: ' Zhangsan ',
Age:18,
Sayname:function () {
alert (this.name);
}
};
JS the third way to create an object (the factory method creates a new instance of an object):
function Createperson (name, age) {
var o = new Object ();
O.name = name;
O.age = age;
O.sayname = function () {
alert (this.name);
}
return o;
}
var person1 = Createperson (' Zhangsan ', 19);
var person2 = Createperson (' Lisi ', 20);
JS the fourth way to create an object (constructor mode):
The memory in this way is as follows:
function person (name, age) {
THIS.name = name;
This.age = age;
This.sayname = function () {
alert (this.name);
}
}
var person1 = new Person (' Zhangsan ', 19);
var person2 = new Person (' Lisi ', 20);
JS the fifth way to create objects (prototype mode):
The memory in this way is as follows:
function person () {}
Person.prototype.name = ' Zhangsan ';
Person.prototype.age = 18;
Person.prototype.sayName = function () {
alert (this.name);
}
var person1 = new Person ();
var person2 = new Person ();
JS the sixth way to create objects (in the form of a literal value of the prototype)
The method of constructing the prototype of the object created in this way no longer points to person, pointing to object.
function person () {}
Person.prototype = {
THIS.name: ' Zhangsan ';
this.age:18;
this.sayName:function {
alert (this.name);
}
};
var person = new person ();
Alert (Person.prototype.constructor = = person); False
Alert (Object.prototype.constructor = = Object); True
Alert (Person.prototype.isPrototypeOf (person)); True
Alert (Object.prototype.isPrototypeOf (person)); True
JS Create object