The main content of this article is from JavaScript advanced programming, object-oriented and prototyping chapters:
1. Factory mode
ECMAScript can create objects through Factory mode:
Factory mode
function CreateObject (name, age) {
var obj = new Object (); Create object
obj.name = name; Add attribute
obj.age = age;
Obj.run = function () { //Add method return
THIS.name + this.age + ' run ... ';
return obj; Returns an object reference
};
var obj1 = CreateObject (' Lee ', MB); Create the first object
var obj2 = CreateObject (' Jack '); Creates a second object
//alert (Obj1.run ()); Prints the Run () method
//alert (Obj2.run ()) of the first object instance; Print the Run () method of the second object instance
//alert (typeof obj1);
Alert (typeof obj2);
Alert (obj1 instanceof Object); True
alert (obj2 instanceof Object);//true
Objects created through Factory mode solve the problem of duplicate instantiation, but the object recognition problem cannot be resolved (all objects are object), so to solve the problem of object recognition, we take the following constructor.
2. Constructor function
constructor creates function person
(name,age) { //All constructor objects are object
this.name=name;
This.age=age;
This.run=function () {return
this.name+this.age+ "ing ...";};
}
; var person1=new person (' zhu1 ', MB);
var person2=new person (' zhu2 ');
Alert (Person1.run ());
Alert (Person2.run ());
Alert (Person1 instanceof Object); Ture
alert (typeof Person2); Person
alert (Person2 instanceof); True
var person3=new Object ();
Person.call (Person3, ' Zhu3 ', 300)//object impersonate, Person3 is object type, impersonate person type
alert (Person3.run ());
Constructor in this: Represents a reference to the current scope object, if this represents a Window object in the global scope, if it is in the constructor body, represents the object declared by the current constructor.
constructor method, and solve the problem of repeated instantiation, there is a solution to the problem of object recognition, compared with the factory method is different:
1. The constructor method does not display the creation object (new object ());
2. Assign the property and method values directly to this;
3. No return statement;
4. However, the use of constructors must be created using the new operator;
The above mentioned is the entire content of this article, I hope you can enjoy.