Create object in JS

Source: Internet
Author: User

Http://www.cnblogs.com/tiwlin/archive/2009/08/06/1540161.html

Http://www.blogjava.net/CopyHoo/articles/244547.html

/* Methods for creating objects :*/

// 1. factory function: the factory function that can be created and returned for a specific type of object ).
Function createcar (scolor ){
VaR car = new object (); // or var car = new object;
// Object Attributes
Car. Color = scolor;
// Object Method
Car. showcolor = function (){
Alert (123 );
}; // Remember, it must be used here; indicates the end

Return car; // return car here; instead of return this. Car; because this. Car is undefined
}
/*
When this function is called, an object is created and all necessary attributes are assigned to it. Two versions of the car object are created using this method,
(Ocar1 and ocar2), they have the same attributes.
Problems with using this method:
1. Semantics does not seem as formal as using new operations with constructors.
2. You must create an object using this method. Every time createcar () is called, showcolor () is created, which means that every object
They all have their own showcolor versions. In fact, every object shares the same function.
Some developers Define object Methods outside the factory function, and then point to this method through attributes. To avoid this problem:
*/
Function createcar2 (scolor ){
VaR car = new object ();
Car. Color = scolor;
Car. showcolor = showcolor;

Return car;
}

Function showcolor (){
Alert (this. Color );
}

VaR ocar1 = createcar ('red ');
VaR ocar2 = createcar ('yellow ');

VaR ocar3 = createcar2 ('blue ');
VaR ocar4 = createcar2 ('black ');

/*
Note that these two objects (ocar3 and ocar4) Call the showcolor attribute method. Although its name is "attribute", it is actually a method !!!
So it is ocar3.showcolor (); not ocar3.showcolor;
*/

Ocar3.showcolor ();
Ocar4.showcolor ();

/*
In this Code, the showcolor () function is defined before the createcar2 () function. Inside createcar2 (), an existing
The pointer to an existing showcolor () function. In terms of function, this solves the problem of repeatedly creating objects, but this function does not look like an object.
.

All these problems have caused the developer to define constructors.
*/

// 2. constructor Mode

Function car (scolor ){
This. Color = scolor;
This. showcolor = function (){
Alert (this. Color );
};
}

VaR car1 = new car ('red ');
Car1.showcolor ();

/*
You may have noticed the first difference. Instead of creating an object in the constructor, you can use the this keyword to use the new
The operator calls the constructor and creates an object before executing the first line of code. Only this can be used to access this object. Then you can
Directly assign this attribute. The default value is the return value of the constructor (you do not need to explicitly use the return operator ).
This method has the same problems as the factory method in terms of management functions.
*/

// 3. Prototype
Function pcar (){
}

Pcar. Prototype. color = "blue ";
VaR pcar1 = new pcar ();

/*
When new car () is called, all attributes of the prototype are immediately assigned to the object to be created, meaning that all pcar instances store
The pointer of the showcolor () function seems to belong to an object from the semantics, so it solves the problems existing in the previous two methods. In addition
This method can also use the instanceof operator to check the object type pointed to by a given variable. Therefore, the following code outputs true:
*/
Alert (pcar1 instanceof pcar); // output "true"

/*
This method looks good. Unfortunately, it is not satisfactory.
1. First, this constructor has no parameters. When the prototype is used, the parameter initialization attribute value cannot be passed to the constructor because pcar1 and
All attributes of pcar2 are equal to "blue"
2. The real problem occurs when the attribute points to an object, instead of a function, function sharing does not cause any problems, but the object is rarely accessed by multiple
Shared by the instance.
*/

// 4. Mixed Constructors/prototype (recommended)
/*
Using constructor and prototype together, you can create objects just like using other programming languages. This concept is very simple, that is, using constructor.
Define all non-function attributes of an object, and define the function attributes (methods) of the object in prototype ).
*/

Function hcar (scolor ){
This. Color = scolor;
This. Drivers = new array ('Mike ', 'sue ');
}

Hcar. Prototype. showcolor = function (){
Alert (this. Color );
}

VaR hcar1 = new hcar ('y color ');
VaR hcar2 = new hcar ('R color ');

Hcar1.drivers. Push ('Matt ');

Alert (hcar1.drivers); // output "Mike, Sue, Matt"
Alert (hcar2.drivers); // output "Mike, Sue"

// 5. Dynamic Prototype (recommended)
/*
Developers who are used to using other development languages feel less harmonious when using a hybrid constructor/prototype. People who criticize the constructor/prototype
It is unreasonable to find attributes in the constructor and find external methods. So they designed a dynamic prototype for a more friendly encoding style.

The basic idea of the dynamic prototype method is the same as that of the hybrid constructor/prototype method. That is, the non-function attributes are defined in the constructor, while the function attributes are used
Prototype property definition. The only difference is that the location of the object method is assigned. The following is the car class that is rewritten using the dynamic prototype method:
*/

Function dcar (scolor ){
This. Color = scolor;
This. Drivers = new array ('Mike ', 'sue ');

If (typeof dcar. _ initialized = 'undefined '){

Dcar. Prototype. showcolor = function (){
Alert (this. Color );
}
}

Dcar. _ initialized = true;
}

VaR dcar1 = new dcar ('y dcar ');
VaR dcar2 = new dcar ('B dcar ');

Dcar1.showcolor ();
Dcar2.showcolor ();

Alert (dcar. _ initialized); // output "true"
Alert (dcar1. _ initialized); // output "undefined"
// 6. Object direct volume, new creation
The simplest way to create an object is that your JavaScript code contains a direct volume of objects. You can also create an object by using the new operator.
VaR empty ={}; // an object with no properties
VaR point = {X: 0, Y: 0 };
VaR Circle = {X: Point. X, Y: Point. Y + 1, radius: 2 };
VaR Homer = {
"Name": "Homer Simpson ",
"Age": 34,
"Married": True,
"Occupation": "plant operator ",
'E-mail ': homer@example.com
};
VaR A = new array (); // create an empty array
VaR d = new date (); // create an object representing the current date and time
VaR r = new Regexp ("JavaScript", "I"); // create a pattern-matching object
After creating an object, we can use the "." operator to create new attributes, reference existing attributes, and set attribute values in the object.
VaR book = new object (); // create an object
Book. Title = "javascript: the definitive guide ";
Book. Chapter1 = new object (); // as an object attribute, nested object
Book. chapter1.title = "Introduction to JavaScript ";
Book. chapter1.pages = 11;
Book. Chapter2 = {Title: "lexical structure", pages: 6 };
Alert ("outline:" + book. Title + "\ n \ t" +
"Chapter 1" + book. chapter1.title + "\ n \ t" +
"Chapter 2" + book. chapter2.title); // read some attributes from the object.
In the preceding example, you can create a value by assigning it to a new property of the object.
The javascript statement mentioned that the for/in statement can be used to traverse the attributes and methods of objects. Delete attribute: delete book. Chapter2;

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.