Getting started with JavaScript Object-Oriented Programming

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.

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.

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.

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.

Copy codeThe Code is as follows:
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.
Copy codeThe Code is as follows: 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 ).
Copy codeThe Code is as follows: 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.

Copy codeThe Code is as follows: 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.
Copy codeThe Code is as follows: 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.
Copy codeThe Code is as follows: 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:
Copy codeThe Code is as follows:
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:
Copy codeThe Code is as follows:
GenderTeller. call (person1); // alerts 'male' e

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.

Copy codeThe Code is as follows:
// 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 (); // check 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 ).
Copy codeCode: 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.

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.