Learning about object usage in Javascript

Source: Internet
Author: User

Javascript is object-oriented, and objects are divided into two types,One is a common object and the other is a method object.. Common objects include "Numbers", "dates", and "user-defined objects" (for example {}).

Let's take a look at "user-defined objects" and "method objects ":

Custom object:

Javascript has an object data type, but this is very different from the objects in C #, VB.net, and Java. For example, in C #, we create an object through a class. A class is equivalent to a template for creating an object and defines the attributes and methods of the object. These objects and methods will always be fixed, we cannot add the attributes and methods of the object at runtime (only inherited during compilation ).

There is no class definition in Javascript, and there is no fixed template when you create an object. You can dynamically add new attributes and Methods. When you dynamically add new attributes, what we can do is to create a new value for this attribute. The following example creates an object and adds the X and Y attributes.

VaR programmer = new object ();
Programmer. Name = "Charles ";
Programmer. Age = 21;
Alert (programmer. Name + ":" + programmer. Age );

Javascript objects are completely different from C # Or VB objects. Javascript objects can be viewed as a set of health/value pairs, and an object. attribute name is used to access an object attribute. We can regard JavaScript objects as Dictionary classes in. NET Framework. We can use the "[]" operator to create object attributes.

VaR programmer = new object ();
Programmer ["name"] = "Charles ";
Programmer ["Age"] = 21;
Document. getelementbyid ("message"). innerhtml = programmer ["name"] + ":" + programmer ["Age"];
Alert (programmer. Name + ":" + programmer. Age );

The above example shows that the two methods for accessing objects are the same. If an attribute is not created, "undefined" is returned ".
We can also add the function as the value of the set of healthy/value pairs, so as to build an object method,

VaR programmer = new object ();
Programmer ["name"] = "Charles ";
Programmer. Age = 21;
Programmer. Speak = function (){
Alert (this. Name + ":" + this ["Age"]);
}
Programmer. Speak ();

The code above does not seem very clear about the attributes and objects contained in an object. The following is another method:

VaR programmer =
{
Name: "Charle ",
Age: 21,
Speak: function () {alert (this. Name + ":" + this. Age );}
}
Programmer. Speak ();

The code above clearly shows the attributes and methods contained in an object, which is used in many JavaScript frameworks. JSON (JavaScript Object Notation) is a lightweight data exchange format, which is easy to interpret and generate by machines and has strict syntax. JSON allows data exchange on the Internet, we can use the eval () method to convert a JSON object to a JavaScript Object.

VaR programmer = "({Name: charleschen, age: 21 })";
VaR P = eval (programmer );
Alert (P. Name + ',' + P. Age );

 

Method object:

A Method object is a function object. In JavaScript, a method is treated as an object.

Function func () {alert ('Hello! ');}
Alert (func. tostring ());

In this example, func is defined as a method, but it contains a tostring () method. It indicates that func is processed as an object here, more accurately, it is a "method object ",

Func. Name = "I am func .";
Alert (func. Name );

 

We can set properties for func, which proves that func is an object. What is the difference between a method object and a common object? First, the method object can be executed. Add a pair of parentheses after it to execute this method object. For example: "func ()"

Therefore, a method object has a dual nature. On the one hand, it can be executed, and on the other hand it can be used as a common object. What does this mean? This means that the method object can be completely independent from other objects. We can compare this with C. In C #, methods must be defined in a class and cannot exist independently. C # is not required.

A Method object is independent of other methods, which means it can be referenced and transmitted randomly. The following is an example:

Function invoke (f ){
F ();
}
Invoke (func );

Pass one method object func to another method object invoke and let the latter execute func when appropriate. This is the so-called "Callback. In addition, this particularity of the method object makes this keyword hard to grasp. There are many related articles in this regard. I will not repeat them here.
In addition to being executable, a method object also has a special function, that is, it can use the new keyword to create a common object.

Each method object is automatically created with a prototype attribute. This attribute has nothing special to do with it. It can be accessed like other attributes and can be assigned values. However, when we use the new keyword to create an object, prototype takes effect: its value (also an object) contains all attributes, will be copied to the newly created object. The following is an example:

Func. Prototype. Name = "prototype of func ";
VaR F = new func ();
Alert (F. Name );

During execution, two dialog boxes are displayed. The next dialog box indicates that the new object F has copied the name attribute from func. prototype. In the previous dialog box, func is executed as a method. You may ask why you need to execute func again at this time? In fact, executing func at this time serves as a "Constructor. To illustrate the image, let's repeat it:

Function func (){
This. Name = "name has been changed ."
}
Func. Prototype. Name = "prototype of func ";
VaR F = new func ();
Alert (F. Name );

You will find that the name attribute of F is not "prototype of func", but is replaced with "name has been changed ". This is the role of the "Constructor" played by the func object method. Therefore, in Javascript, the following three steps are performed to create an object with the New Keyword:

  1. Create a new common object;
  2. Copy all properties of the prototype property of the method object to the new common object.
  3. Use a new common object as the context to execute the method object.

A statement like "New func ()" can be described as "Creating a new object from func ". In short, the only special feature of the prototype attribute is that it is time to create a new object.

So we can use this. For example, there are two method objects A and B. Since the new object created from a contains all. attribute of prototype, then I will assign it to B. prototype, so the new object created from B does not have the same attribute? The Code is as follows:

A. Prototype. Hello = function () {alert ('Hello! ');}
B. Prototype = new ();
New B (). Hello ();

This is the so-called "inheritance" of JavaScript. Its essence is the copy of attributes. prototype is used here. If prototype is not used, a loop is used, and the effect is the same. The so-called "Multi-inheritance" is naturally copied everywhere.
The object-oriented principle in Javascript is the above. I didn't mention the concept of "class" from beginning to end, because JavaScript didn't have "class. Can there be no class for object orientation? Of course. It is unreasonable to have a class first and then an object again, because the class is originally summarized from the object, and the object has another class first. This is reasonable. As shown below:

Code
VaR o ={}; // I found something.
O. Eat = function () {return "I am eating."} // I found it will eat;
O. Sleep = function () {return "Zzzzzz"} // I found it would sleep;
O. Talk = function () {return "Hi! "} // I found it talking;
O. Think = function () {return "Hmmm"} // I found that it still thinks.

VaR human = new function (); // I decided to name it "person ".
Human. Prototype = O; // This item represents the concept of all "people.

VaR H = new human (); // when I find something the same as it,
Alert (H. Talk () // I will know that it is also a "person!

 

The above content is not original. It is taken from the following two articles. In order to facilitate learning, some modifications have been made, so we have summarized it into an article: hope to help beginners:

Original article: http://www.javaeye.com/topic/155109

Http://www.cnblogs.com/young18/archive/2007/05/28/761927.html
 

Related Article

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.