Originally wanted to brush a codewar on the algorithm, the results looked at half a day did not fix (cover face fled), the level of too vegetables hurt, ah, heart meditation three: I will return. And then I'll just wrap it up. JS create objects in several ways:
No1. Object literal:
This method is usually used relatively more, for a chestnut:
var person={
Name: ' Robert ', job: ' Web develop ', sex: ' Male ', skill:funcion () { console.log (' Just coding ') } };
This method is simple and rough, who use who know, the shortcomings are quite obvious, can not be reused.
No2. Oject constructor:
This method does not draw the advantage of object literals, but also preserves the disadvantage of object literals
var person=new Object (); Person.name= ' Robert '; person.job= ' web develop '; person.sex= ' male '; Person.skill=funcion () { console.log (' Just coding ') };
No3. Factory mode:
The factory pattern is much more interesting, creating a new object from the encapsulated function, returning the object, and changing the property values of the new object through the parameters.
function Factory (name,job,sex) { var obj=new Object (); Obj.name= name; obj.job= job; obj.sex= sex; Obj.skill=function () { console.log (' Hello World ') };
return obj;
}
var person = factory (' Robert ', ' web develop ', ' male ');
The code can be reused, and you can customize the value of the property, flattered
No4. Constructor mode:
Factory mode each time an object is created and returned, the constructor pattern means that it is not so troublesome at all, just a new one at a time.
function Person (name,job,sex) { this.name= name; this.job= job; this.sex= sex; This.skill=function () { console.log (' Hello World ') }; var person = new Person (' Robert ', ' web develop ', ' male ');
No5. Prototype mode:
Prototype mode after looking at the constructor mode, smile and say, "Your method is not shared, let me improve it";
function person () {} person.prototype.name= ' Robert '; person.prototype.job= ' web develop '; person.prototype.sex= ' male '; Person.prototype.skill=function () { console.log (' Hello World ') };var person = new person ();
Good is good, the properties and methods are common, not what we want, combined with the advantages of prototype mode and constructor mode, one, mixed mode debut
No6. Mixed mode:
More useless, or direct show Code good,
function Person (name,job,sex) { this.name= name; this.job= job; this.sex= sex;} Person.prototype.skill=function () { console.log (' Hello World ')};var person = new Person (' Robert ', ' web develop ', ' Male ');
A word Summary: attribute customization, method sharing
JS create objects in several ways