Basic knowledge of object-oriented programming in JavaScript

Source: Internet
Author: User
This article mainly introduces the basics of JavaScript object-oriented programming and is an important knowledge concept in JavaScript beginners. For more information, see New Understanding of object-oriented
To demonstrate that JavaScript is a thorough object-oriented language, it is necessary to start with the object-oriented concept and discuss several concepts of object-oriented:

  1. Everything is an object
  2. Objects are encapsulated and inherited.
  3. Communication is used between objects to hide information.

Based on these three points, C ++ is a semi-object-oriented semi-process language, because although it implements class encapsulation, inheritance, and polymorphism, however, there are non-object global functions and variables. Java and C # are completely object-oriented languages. They organize functions and variables in the form of classes so that they cannot be separated from objects. But here the function itself is a process, only attached to a class.

However, object-oriented is just a concept or programming idea. It should not depend on a language. For example, Java uses the object-oriented idea to construct its language, which implements mechanisms such as class, inheritance, derivation, polymorphism, and interface. However, these mechanisms are only a means to implement object-oriented programming, rather than necessary. In other words, a language can choose an appropriate method based on its own characteristics to implement object-oriented. Therefore, most programmers first learn or use advanced compilation languages such as Java and C ++ (although Java is semi-compiled and semi-interpreted, it is generally explained as a compilation type ), therefore, the "class" Object-Oriented implementation method is accepted first, so that when learning the script language, it is customary to use the concepts in class-based object-oriented language to determine whether the language is an object-oriented language or whether it has the object-oriented feature. This is one of the important reasons that impede programmers from learning and mastering JavaScript.
In fact, the JavaScript language implements object-oriented programming through a prototype method. Next we will discuss the differences between class-based object-oriented methods and prototype-based Object-Oriented Methods in constructing the objective world.
Comparison between class-based and prototype-Based Object-Oriented Methods
In the class-based object-oriented approach, objects are generated by classes. In the prototype-based object-oriented approach, objects are constructed by constructor using prototype. Here is an example of the objective world to illustrate the differences between the two methods of cognition. For example, a factory creates a car. On the one hand, a worker must refer to an engineering drawing to design how the car should be made. The engineering drawings here are like classes in languages, and cars are made by class. On the other hand, workers and machines (equivalent to constructor) the vehicle is constructed using various components, such as the engine, tires, and steering wheel (equivalent to the prototype attributes.
As a matter of fact, there is still debate about who expresses the idea of object-oriented more thoroughly. However, I believe that the original type of object-oriented method is a more thorough object-oriented method, for the following reasons:
First of all, objects in the objective world are produced by the construction of other objects. Abstract "drawings" cannot produce "cars". That is to say, A class is an abstract concept rather than an entity, and an object is generated;
Secondly, according to the most basic object-oriented rule that everything is an object, the class itself is not an object. However, constructor in the prototype method) prototype is also an object constructed by other objects in prototype mode.
Thirdly, in the class-Oriented Object Language, the object state is held by the object instance, and the object behavior method) it is held by the class that declares the object, and only the structure and method of the object can be inherited. In the original type object-oriented language, the behavior and status of the object belong to the object itself, and can be inherited together (reference resources), which is closer to objective reality.
Finally, in order to make up for the inconvenience of using global functions and variables in the process-oriented language, the Class-oriented object-oriented language such as Java allows you to declare static attributes and static methods in the class. In fact, there is no static concept in the objective world, because everything is an object! In the original type object-oriented language, in addition to the built-in object, the existence of global objects, methods, or attributes is not allowed and there is no static concept. All language elements (primitive) must depend on objects. However, due to the features of functional language, the language elements depend on objects that change with the context of the runtime. this is reflected in the changes of the this pointer. It is precisely this kind of feature that is closer to the natural viewpoint that "Everything belongs, and the universe is the foundation of the survival of everything.


Basic JavaScript Object-Oriented Knowledge

Although JavaScript itself does not have the concept of a class, it still has the object-oriented feature, although it is different from the common object-oriented language.

The simple method for creating an object is as follows:

Function myObject () {}; Generally, there are two methods for creating objects in JavaScript: function constructor and literal method. The above method belongs to function constructor. The following is an example of the literal method: var myObject = {};

If you only need an object, but do not need other instances of the object, we recommend that you use the literal method. If multiple instances of an object are required, the function constructor is recommended.
Define attributes and Methods

Function constructor:

function myObject() { this.iAm = 'an object'; this.whatAmI = function() { console.log('I am ' + this.iAm); };};

Literal method:

var myObject = { iAm : 'an object', whatAmI : function() { console.log('I am ' + this.iAm); }};

The objects created by the preceding two methods have an attribute named "iAm" and a method named "whatAmI. The property is the variable in the object, and the method is the function in the object.

How to obtain attributes and call methods:

var w = myObject.iAm;myObject.whatAmI();

When calling a method, brackets must be added. If no brackets are added, it is only a reference to the Return method.
Differences between the two object creation methods

  • When defining attributes and methods in the function constructor, you must use the prefix this, which is not required by the literal method.
  • The function constructor uses = when assigning values to attributes and methods, and the literal method uses :.
  • If there are multiple attributes or methods, use the; Separator in the function constructor and the literal separator.

For an object created by using the literal method, you can directly call its attributes or methods by referencing the object:

myObject.whatAmI();

For function constructor, you must create an instance of an object to call its attributes or methods:

var myNewObject = new myObject();myNewObject.whatAmI();

Use constructors

Now let's return to the previous function constructor:

function myObject() { this.iAm = 'an object'; this.whatAmI = function() { console.log('I am ' + this.iAm); };};

In fact, it looks like a function. Since it is a function, can you pass parameters to it? Slightly modify the code:

function myObject(what) { this.iAm = what; this.whatAmI = function(language) { console.log('I am ' + this.iAm + ' of the ' + language + ' language'); };};

Instantiate the object and input the following parameters:

var myNewObject = new myObject('an object');myNewObject.whatAmI('JavaScript');

The program outputs I am an object of the JavaScript language.
Which of the following methods can I use to create an object?

For the literal method, because it does not need to be instantiated, if the value of an object is modified, the value of this object will be permanently modified and accessed anywhere else, all are modified values. For the function constructor, the value of the instance is modified when it is modified. It can instantiate N objects, and each object can have its own values without interfering with each other. Compare the following code.

First look at the literal method:

var myObjectLiteral = { myProperty : 'this is a property'};console.log(myObjectLiteral.myProperty); // log 'this is a property'myObjectLiteral.myProperty = 'this is a new property';console.log(myObjectLiteral.myProperty); // log 'this is a new property'

Even if a new variable is created pointing to this object, the result is the same:

var myObjectLiteral = { myProperty : 'this is a property'};console.log(myObjectLiteral.myProperty); // log 'this is a property'var sameObject = myObjectLiteral;myObjectLiteral.myProperty = 'this is a new property';console.log(sameObject.myProperty); // log 'this is a new property'

Let's look at the function construction method:

// Var myObjectConstructor = function () {this. myProperty = 'this is a properties'}; // instantiate an object var constructorOne = new myObjectConstructor (); // instantiate the second object var constructorTwo = new myObjectConstructor (); // output the console. log (constructorOne. myProperty); // log 'this is a properties' // output console. log (constructorTwo. myProperty); // log 'this is a properties' is the same as expected. The attribute values of the two objects are the same. What if we repair the value of one of the objects? // Var myObjectConstructor = function () {this. myProperty = 'this is a properties';}; // instantiate an object var constructorOne = new myObjectConstructor (); // modify the object's attribute constructorOne. myProperty = 'this is a new properties'; // instantiate the second object var constructorTwo = new myObjectConstructor (); // output alert (constructorOne. myProperty); // log 'this is a new properties' // output alert (constructorTwo. myProperty); // log 'this is a properties'

We can see that different objects instantiated by using function constructor are independent of each other and can have different values. Therefore, the method used to create an object depends on the actual situation.

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.