var New = "Dang"=function() {returnthis. name+ this. age+ ' running: ';} Alert (Box.run ());
Creating objects above requires a lot of code to create similar objects, such as when creating a Box2
Create a centralized instantiation method, Factory mode
functionCreateObject (name,age) {varobj =NewObject (); Obj.name=name; Obj.age=Age ; Obj.run=function(){ return This. name+ This. age+ "in operation"; }; returnObj//Be sure to return the object};functionCreateObject2 (name,age) {varobj =NewObject (); Obj.name=name; Obj.age=Age ; Obj.run=function(){ return This. name+ This. age+ "in operation"; }; returnObj//Be sure to return the object};varBox1 = CreateObject ("Lee", 100);varBox2 = CreateObject ("Jack", 200);varBox3 = CreateObject2 ("lll", 111);//is object, which is to identify the problem, because there is no way to figure out exactly which object they are an instance of. alert (Box1.run ()); alert (Box2.run ());
//constructor creation, solve the above recognition problem, you can find out exactly which object they are an instance offunctionBox (name,age) {//Not medicinal name This. Name =name; This. Age =Age ; This. Run =function(){ return This. name+ This. age+ "Yinxingzhong"; }; //semicolon to add}functionBox2 (name,age) { This. Name =name; This. Age =Age ; This. Run =function(){ return This. name+ This. age+ "Yinxingzhong"; }; //semicolon to add}
1. The constructor does not have a new Object, but the background will automatically var obj = new Objeck ();
2. This is equivalent to obj
3. No return statement
1. The constructor is also a function, with the first letter capitalized
2. The new constructor must be instantiated
var New Box ("Lee", +); var New Box ("Jack", +); var New Box2 ("KK",instanceof box); // true
Another: impersonating a call
// Object impersonating a call var New Object (); Box.call (O,"Lee", +); alert (O.run ());
Creation of objects