Creating objects
JS creates objects in several ways:
1, Factory mode.
2, constructor mode.
3, prototype mode.
4, combining the constructor pattern with the prototype mode
(a): Factory mode
function Createperson (name) { varnew Object (); = name; function () { alert (this. Name); } return obj;} var // no need to use newperson.show ();
(b), the constructor mode:
The function name of the constructor begins with uppercase, and the other functions are lowercase
//constructor ModefunctionPerson (name, age) { This. Name =name; varsex = Sex//Private This. Show =function() {alert (sex); } }varPerson1 =NewPerson ("ym", "Nan"); alert (person1.name); //ymAlert (Person2.sex)//undefinedPerson1.show ();//nan
The difference between the construction method pattern and the Factory mode:
1, the Creation object is not displayed.
2, assign the value directly to the This object.
3, there is no return statement.
Problems with constructors:
When an object has more than one instance, all of the methods of those instances are different because it is created again.
//constructor ModefunctionPerson (name, sex) { This. Name =name; varsex = sex;//Private This. Show =function() {alert (sex); }}varPerson1 =NewPerson (' ym ', ' nan ');varPerson2 =NewPerson (' JH ', ' NV ');//alert (person1 instanceof person); TrueAlert (Person1.show = = person2.show);//false
(iii), prototype mode
Pros: You can have all object instances share the properties and methods that it contains.
// 6. Prototype Mode function = { "ym", ' nan ', function() { alert ( This . Name); var New Person2 (); var New = = b.show); // true
Problem with prototype mode:
functionPerson2 () {} Person2.prototype={name:"YM", Sex:' Nan ', love: [' A ', ' B '], show:function() {alert ( This. Name); }} varA =NewPerson2 (); A.love.push (C);varb =NewPerson2 (); A.love.push (' d ');//alert (a.show = = b.show);alert (a.love);//ABCDalert (b.love);//ABCD
(iv), combined use of prototype mode and constructor mode
From the above example, we can know that the constructor pattern, the method of creation is different, is the instance own, and the prototype schema definition of the properties and methods are shared, then the combination of use is really perfect.
//6. Mixed ModefunctionPerfect (name, sex) { This. Name =name; This. Sex =sex; This. Love = [' A ', ' B '];} Perfect.prototype={constructor:perfect, show:function() {alert ( This. Love); }}varA =NewPerfect (' A ', ' Nan ');varb =NewPerfect (' B ', ' NV '); A.love.push (C); B.love.push (' d '); A.show (); //ABCB.show ();//Abd
Object-oriented correlation