Creation of objects

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.