Method One: Object Type method
var person = new Object ();
Person.name= "Alisa";
Person.age= "16";
person.sex= "female";
Person.sayname = function () {
return this.name;
}
Method Two: Object Literal method
var person={
Name: "Alisa",
Age:16,
Sex: "Female",
Sayname:function () {
return this.name;
}
}
Using method One and method two, the biggest drawback is that if you need to create many JavaScript objects with the same properties but different property values, there will be a lot of duplicated code.
There is no concept of class in JavaScript, which is different from Java, so you cannot create many similar objects by creating a class and then building an object. In this case, can we create a method in which the object is created, and each time the method is called, a different argument is passed to create an object. Based on this idea, the developer used the factory model.
Method Three: Factory mode
function Createperson (name,age,sex) {
var person = new Object ();
Person.name=name;
Person.age=age;
Person.sex=sex;
Person.sayname = function () {
return this.name;
}
return person;
}
var P1=createperson ("Alisa", +, "female");
var p2= createperson ("Lily", "female");
Ways to create JavaScript objects