Object-oriented JavaScript-tutorials from Mozilla's official website

Source: Internet
Author: User

 

Despite the differences between object-oriented JavaScript and other languages, and this has caused some controversy, there is no doubt that JavaScript has powerful Object-Oriented Programming capabilities. This article first introduces Object-Oriented Programming, then reviews the JavaScript Object Model, and finally demonstrates the concept of object-oriented programming in JavaScript.

Directory

Javascript Review
Object-Oriented Programming
Terminology
Prototype-based programming
Javascript Object-Oriented Programming
5.1. core objects
5.2. Custom object
5.2.1. Class
5.2.2. Object (class instance)
5.2.3. Constructor
5.2.4. attributes (Object Attributes)
5.2.5. Method
5.2.6. Inheritance
5.2.7. Encapsulation
5.2.8. Abstraction
5.2.9. Polymorphism
Prompt
References

Despite the differences between object-oriented JavaScript and other languages, and this has caused some controversy, there is no doubt that JavaScript has powerful Object-Oriented Programming capabilities.

This article first introduces Object-Oriented Programming, then reviews the JavaScript Object Model, and finally demonstrates the concept of object-oriented programming in JavaScript.
Javascript Review

If you have no idea about JavaScript concepts such as variables, types, functions, and scopes, then you can read and reintroduce these theme in JavaScript. You can also refer to the Javascript 1.5 core guide
Object-Oriented Programming

Object-Oriented programming is a programming paradigm that uses abstraction to create models based on the real world. It uses several previously established paradigm technologies, including modularity, polymorphism, and encapsulation ). Today, many popular programming languages (such as Java, JavaScript, C #, C ++, Python, PHP, Ruby, and objective-c) Support Object-Oriented Programming (OOP ).

Object-Oriented programming can be seen as using a set of collaborative objects for software design, which is opposite to the traditional viewpoint. The traditional viewpoint regards a program as a set of functions or simplifies it into a list of computer commands. In object-oriented programming, each object has the following capabilities: receive messages, process data, and send messages to other objects. Each object can be considered as an independent small machine with different roles or responsibilities.

Object-Oriented programming aims to improve programming flexibility and maintainability, and is widely used in large-scale software engineering. Because it attaches great importance to modularity, object-oriented Code aims to make development easier and easier to understand later, and it is less modular than programming methods, this makes it easier to analyze, encode, and understand complex situations and procedures. [2]
Terminology

Class)
~ Define the characteristics of an object (characteristics ).
Object)
~ Instance ).
Property)
~ A characteristic object, such as color.
Method)
~ A certain object capability, such as walking.
Constructor)
~ Instantiation.
Inheritance)
~ A class can inherit the features of another class.
Encapsulation)
~ A class only defines the features of the object, and a method only defines how the method is executed.
Abstract action)
~ Combine the complex inheritance, methods, and attributes of an object, and must be able to simulate a realistic model.
Polymorphism)
~ Different classes may define the same methods or attributes.

For more information about object-oriented programming, see the object-oriented programming entry in Wikipedia.
Prototype-based programming

Prototype-based programming is an object-oriented programming style, where classes do not exist and behavior is reused (inherited in a class-based language) it is done by whitewashing the existing objects that act as the prototype. This mode is also called class-less, prototype-oriented, or instance-based programming.

The initial (and very standard) Example of prototype-based language is the self programming language developed by David Ungar and Randall Smith. However, this classless programming style has become increasingly popular recently and has been adopted by some programming languages, for example, avascript, Cecil, newtonscript, Io, moo, REBOL, Kevo, Squeak (when using the viewer framework to manipulate the morphic component), and other languages. [2]
Javascript Object-Oriented Programming
Core objects)

Javascript has several objects contained in its core, such as math, object, array, and string. The following example shows how to use the random number () method of the math object to obtain a random number.

Alert (math. Random ());

Tip: this example and all other examples assume that the function name alert has been defined globally (just as alert is included in the Web browser ). The alert function is not actually part of JavaScript itself.

For the list of JavaScript core objects, see JavaScript 1.5 core reference: global objects ).

Every object in Javascript is an instance of an object, and thus inherits all its attributes and methods.
Custom object (custom objects)
The class)

Javascript is a prototype-based language that does not contain Class statement that can be found in C ++ or Java ). Sometimes this will confuse some programmers who are used to programming ages with a class statement. However, JavaScript uses functions as classes. Defining a class is simply to defining a function. In the following example, we define a new class named person.

Function person (){}

Object (class instance) (the object (class instance ))

To create a new instance of the OBJ object, we use the statement new OBJ and assign the result (whose type is OBJ) to a variable for later access.

In the following example, we first define the class named person, and then create two instances (person1 and person2 ).

Function person (){}
VaR person1 = new person ();
VaR person2 = new person ();

You can also refer to the new instantiation substitution method object. Create.

The constructor)

The constructor is called when the object instance is instantiated (the moment when the object instance is created. Constructor is a class method. In JavaScript, functions are used as the constructor of the object. Therefore, you do not need to explicitly define a constructor method. Every action declared in the class is executed during instantiation.

Constructors are used to set object properties or call methods to prepare for using this object. This article will introduce how to add a class method and its definition by using a different syntax.

In the following example, the constructor of the person class displays a warning box when the person class is instantiated.

Function person (){
Alert ('person instantiated ');
}

VaR person1 = new person ();
VaR person2 = new person ();

The Property (Object attribute ))

Attributes are variables contained in the class; each object instance has these attributes. The attribute should be set in the prototype attribute of the class (function) to inherit the class and work normally.

In the class, the Operation attribute is implemented through the this keyword, and this references the current object. For external class access (read or write), an attribute must use the following syntax: InstanceName. property, which is the same as the syntax used in C ++, Java, and other languages. (Use the syntax of this. property inside the class to obtain or set the attribute value ).

In the following example, we define the gender (gender) attribute for the person class and then this attribute during initialization.

Function person (gender ){
This. Gender = gender;
Alert ('person instantiated ');
}

VaR person1 = new person ('male'); // male: Male
VaR person2 = new person ('female'); // female: Female

// Display the gender of person1
Alert ('person1 is a' + person1.gender); // person1 is a male

Method (the methods)

Methods follow the same logic as attributes. The difference is that they are functions and are defined as functions. The call method is similar to the access attribute. However, you must add () at the end of the method name. There may be parameters (arguments ). Define a method to specify a function for a naming attribute of the prototype attribute. the name assigned to the function is the name of the method called on the object.

In the following example, we define and use the sayhello () method for the person class.

Function person (gender ){
This. Gender = gender;
Alert ('person instantiated ');
}

Person. Prototype. sayhello = function ()
{
Alert ('hello ');
};

VaR person1 = new person ('male ');
VaR person2 = new person ('female ');

// Call the sayhello method of person.
Person1.sayhello (); // hello

In JavaScript, a method is a common function object bound to a class/object as an attribute, which means that it can be called "out of the context. Consider the following sample code:

Function person (gender ){
This. Gender = gender;
}

Person. Prototype. saygender = function ()
{
Alert (this. Gender );
};

VaR person1 = new person ('male ');
VaR genderteller = person1.saygender;

Person1.saygender (); // alerts 'male'
Genderteller (); // alerts undefined
Alert (genderteller === person1.saygender); // alerts true
Alert (genderteller === person. Prototype. saygender); // alerts true

This example demonstrates multiple concepts at a time. This indicates that there is no "Object-based method (Per-object methods)" In JavaScript, because all references to this method point to the same function, that is, the function we initially defined on the prototype. When a function is called as a method (or attribute), JavaScript binds the current "object context" to a specific "this" variable. This is equivalent to calling the "call" method of the function object, as shown below:

Genderteller. Call (person1); // alerts 'male'

For more information, see function. Call and function. Apply.

Inheritance)

Inheritance is a method used to create a class that is specialized for one or more classes. (JavaScript only supports single-class inheritance ). This special class is usually called child, while other classes are usually called parent classes ). In JavaScript, to complete inheritance, You need to assign the instance of the parent class to the subclass, and then specializing the subclass ).

Tip: prototype of the subclass not detected by JavaScript. constructor (prototype constructor), refer to core JavaScript 1.5 core reference: Global Objects: object: Prototype attribute, so we must manually specify this value.

In the following example, we define the student class as a subclass of person. Then we redefine the sayhello () method and add the saygoodbye () method.

// Define the person class
Function person (){}

Person. Prototype. Walk = function (){
Alert ('I am walking! ');
};
Person. Prototype. sayhello = function (){
Alert ('hello ');
};

// Define the student class
Function student (){
// Call the parent class Constructor
Person. Call (this );
}

// Inherit the person
Student. Prototype = new person ();

// Corrected the constructor pointer because it points to person
Student. Prototype. constructor = student;

// Replace the sayhello Method
Student. Prototype. sayhello = function (){
Alert ('Hi, I am a student ');
}

// Add the saygoodbye Method
Student. Prototype. saygoodbye = function (){
Alert ('Goodbye ');
}

VaR student1 = new student ();
Student1.sayhello ();
Student1.walk ();
Student1.saygoodbye ();

// Verify inheritance
Alert (student1 instanceof person); // true
Alert (student1 instanceof student); // true

Encapsulation

In the preceding example, student does not need to know how the walk () method of the person class is implemented, but can still be used. Student class does not need to explicitly define this method, unless we want to change it. This is called encapsulation, so that each class inherits the method of its parent class and only needs to define what it wants to change.
Abstraction

Abstract is a mechanism that allows modeling of the current part of the problem being processed. This can be achieved through inheritance or composition. Javascript implements specialization through inheritance, and combines class instances into attribute values of other objects.

The function class of JavaScript inherits from the object class (this indicates the model is special), and the function. Prototype attribute is an instance of the object (this indicates the combination ).

VaR Foo = function (){};
Alert ('foo is a function: '+ (FOO instanceof function ));
Alert ('foo. prototype is an object: '+ (FOO. Prototype instanceof object ));

Polymorphism

Just as all methods and attributes are defined inside the prototype attributes, different classes can define methods with the same name. The scope of methods is limited to the classes that define them. This is true only when there is no parent-child relationship between two classes (when a class does not inherit from other classes in the inheritance chain.
Prompt

The object-oriented programming implementation technology proposed in this article is not only applicable to Javascript, because it is very flexible in terms of how to implement object-oriented programming.

Similarly, the technology presented here neither uses any language skills (Language hacks) nor imitates the object theory implementation of other languages.

There are other more advanced object-oriented programming techniques in Javascript, but the content is beyond the scope of this introductory article.
References

Mozilla. "Javascript 1.5 core guide ",

Http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide

Wikipedia. "Object-Oriented Programming", http://en.wikipedia.org/wiki/Object-oriented_programming

 

 

 

 

 

 

 

 

 

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.