1. Built-in object creation
var girl=new Object ();
Girl.name= ' HXL ';
Console.log (typeof girl);
2. Factory mode, parasitic constructor mode
function person (name) {
var p=new Object ();//internal instantiation of
P.name=name;
P.say=function () {
console.log (' My name is ' + p.name);
}
Return p;//Note: Must be returned
}
var girl=person (' Haoxioli ');
Girl.say ();
3. Constructor creation
var product=function (name) {
this.name=name;
This.buy=function () {
console.log (' The sign of my dress is ' +this.name ');
}
var pro=new Product (' jeanswest ');
Pro.buy ();
4. prototype creation, disadvantage: Each property in the instance may be different
var role=function () {}
role.prototype.name={nickname: ' nickname '};
var boy=new role ();
Boy.name.nickname= ' Liu Xiaobing ';
Console.log (boy.name.nickName);//Liu Xiaobing
var girl=new role ();
Girl.name.nickname= ' Shang ';
Console.log (boy.name.nickName);//Shang, because the instance object can modify the value of the referenced object in the prototype
Console.log (girl.name.nickName);//Shang
5. Blending Mode: Prototype + construction, you can put the properties that do not allow the instance to be modified in the constructor, can be modified in the prototype
var role=function () {
this.name={nickname: ' aaa '};
}
role.prototype.age=30;
var boy=new role ();
Boy.name.nickname= ' Boy ';
Console.log (boy.name.nickName);//boy
var girl=new role ();
Girl.name.nickname= ' girl ';
Console.log (boy.name.nickName);//boy, the instance does not modify the values in the constructor
Console.log (girl.name.nickName);//girl
6. Literal form
var cat={
name: ' Lucy ',
age:3,
sex: ' Mother '
};//converts an object to a string
Console.log (Json.stringify (cat));//{" Name ":" Lucy "," Age ": 3," Sex ":" Mother "}
var dog= ' {" name ":" John "," Sex ":" Gong "} ';
Console.log (Json.parse (dog). name);//convert String to Object
7. Copy Mode
function Extend (Tar,source) {for
(var i in source) {
tar[i]=source[i];
}
return tar;
}
var boy={name: ' Drunken warrior ', age:20};
var person=extend ({},boy);
Console.log (Person.name);
8. Third-party frameworks
First introduce package
<script src= ' js/base2.js ' ></script>
//base2 Framework, Base.extend and constructor are all fixed usage
var animal=base.extend ({
constructor:function (name) {
this.name=name;
},
say:function (MEG) {
Console.log (this.name+ ":" +meg);
}
);
New Animal (' Lily '). Say (' Fish ');
Another third party framework
<script src= ' js/simplejavascriptinheritance.js ' ></script>
//simplejavascriptinheritance Framework, Class.extend and init are fixed usage
var person=class.extend ({
init:function (name) {
this.name=name;
}
});
var p=new person ();
P.name= ' over ';
Console.log (P.name);
More than this JS in a variety of ways to create an object is a small series to share all the content, I hope to give you a reference, but also hope that we support the cloud-dwelling community.