Introduction to JavaScript object-oriented Programming Basics

Source: Internet
Author: User
Tags object model

While there are some arguments about the difference between object-oriented JavaScript and other languages, there is no doubt that JavaScript has powerful object-oriented programming capabilities

This article starts with introducing object-oriented programming, then reviews the JavaScript object model, and finally demonstrates the Object-oriented programming concept in JavaScript.

JavaScript review

If you feel like you have no idea what JavaScript concepts like variables (variables), types (types), Functions (functions), and scope (scope) are, then you can read the topics in the new JavaScript. You can also check out the JavaScript 1.5 core guide

Object Oriented Programming

Object-oriented programming is a programming paradigm (paradigm) that uses abstractions to create models based on the real world. It uses several previously established paradigm techniques, including modular (modularity), polymorphic (polymorphism), and encapsulation (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 thought of as using a collection of collaborative objects for software design, contrary to conventional wisdom, the traditional view of a program as a collection of functions, or as a simplification of a list of computer commands. In object-oriented programming, each object has the ability to receive messages, process data, and send messages to other objects. Each object can be considered as a separate small machine with different roles or responsibilities.
Object-oriented programming is designed to promote greater flexibility and maintainability for programming, and is widely popular in large-scale software engineering. Because it attaches great importance to modularity, object-oriented code is designed to make development simpler, easier to understand later, and more straightforward to analyze, encode, and understand complex situations and procedures relative to less modular programming methods.

Special terminology

Classes (Class)
~ Defines the characteristics of the object (characteristics).
Objects (object)
The instance of the ~ Class (Instance).
Properties (property)
~ An object feature (characteristic), such as a color.
Methods (method)
~ Some kind of object ability, such as walking.
Constructors (constructor)
~ The method that is called when instantiating (instantiation).
Inheritance (inheritance)
~ A class can inherit a feature from another class.
Encapsulation (encapsulation)
~ A class defines only the characteristics of the object, and a method only defines how the method executes.
Abstract (abstraction)
~ Combines complex inheritance, methods, and attributes of an object, and must be able to simulate a realistic model.
Polymorphism (polymorphism)
~ Different classes may define the same method or property.
For further description of object-oriented programming, see Wikipedia's object-oriented programming entry.

Prototype-based programming

Prototype based programming (Prototype-based programming) is an object-oriented programming style where classes (classes) do not exist, and behavior reuse (called Inheritance in a class-based language) is done by whitewashing existing objects that act as prototypes. This pattern is also referred to as class-less, prototype-oriented (prototype-oriented), or case-based (instance-based) programming.
The initial (and very canonical) example of a prototype language is the Self programming language developed by David Ungar and Randall Smith. However, this type of programming style has become increasingly popular recently and has been adopted by some programming languages, such as Avascript, Cecil, NewtonScript, Io, MOO, REBOL, Kevo, Squeak (when using the viewer frame to manipulate morphic components), and several other languages.

JavaScript Object-Oriented programming

Core objects (Cores Objects)

JavaScript has several objects that are contained in its core, such as Math, object, Array, and string. The following example shows how to use the random () method of the Math object to get a random number.

Copy Code code as follows:

Alert (Math.random ());

Tip: This example and all other examples assume that the function name alert is defined globally, just as alert is contained in a Web browser. The alert function is not actually part of the JavaScript itself.

JavaScript core objects list, see JavaScript 1.5 Core Reference: Global Objects.

Each object in JavaScript is an instance of an object, and therefore inherits all of its properties and methods.

customizing objects (Custom Objects)

Class (The Class)

JavaScript is a prototype-based language that does not contain class declarations (class statement) that can be found in C + + or java. Sometimes this is confusing to programmers who are accustomed to having class declaration languages (languages with a class statement). However, JavaScript uses functions (functions) as classes. Defining a class is simple enough to define a function. In the following example, we define a new class named person.

Copy Code code as follows:
function person () {}


object (Instance of Class) (the object Instance)

To create a new instance of the Obj object, we use the statement new obj and assign the result (its type is obj) to a variable (variable) for later access.
In the following example, we first define a class named person, and then create two instances (Person1 and Person2).
Copy Code code as follows:
function person () {}
var person1 = new Person ();
var person2 = new Person ();

You can also see the new instantiation workaround object.create.

Constructor (the constructor)

The constructor is invoked when instantiated (the instant that the object instance is created). Constructors are a method of a class. In JavaScript, a function is used as the constructor of the object, so there is no need to explicitly define a constructor method. Each behavior declared in a class executes when instantiated.

constructor is used to set object properties or invoke methods to prepare for using the object. Later in this article, you add a class method and its definition by using a different syntax.

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

Copy Code code as follows:
function person () {
Alert (' person instantiated ');
}
var person1 = new Person ();
var person2 = new Person ();

Properties (object attribute) (the property)

A property is a variable that is contained in a class, and each object instance has these properties. The property should be set in the prototype (prototype) property of the Class (function) in order to inherit the normal work.
Manipulating properties in a class is implemented through the This keyword, this refers to the current object. accessing (reading or writing) an attribute outside of a class takes the following syntax: Instancename.property; This is the same syntax used in C + +, Java, and some other languages. (This is used inside the class.) property to get or set the attribute value.

In the following example, we define the gender (gender) attribute for the person class, and then define the property at initialization time.

Copy Code code 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
Show Person1 's Sex
Alert (' Person1 is a ' + Person1.gender); Person1 is a Male

Method (The methods)

Methods follow the same logic as attributes, except that they are functions and are defined as functions. The calling method is similar to the Access property, but you may have a parameter (arguments) if you want to add () at the end of the method name. Define a method that specifies a function for a named property on the prototype property of the class; the name that the function is assigned to is the name of the method invoked on the object.
In the following example, we define and use the SayHello () method for the person class.

Copy Code code 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 '); Invokes the SayHello method of person.
Person1.sayhello (); Hello

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

Copy Code code 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 several concepts at a time. This indicates that there is no "object-based method (Per-object methods)" in JavaScript because all references to the method point to exactly the same function, namely, the function we initially defined on the prototype. When a function is called as a method (or rather, a property), JavaScript binds the current object context to the specific "this" variable. This is equivalent to the call method that calls the function object, as follows:
Copy Code code as follows:

Genderteller.call (Person1); Alerts ' Male ' E

For more information, please refer to Function.call and function.apply

Inheritance (inheritance)

Inheritance is a way to create a class that is a specialized version of one or more classes. (JavaScript only supports single class inheritance). This private class is often referred to as a subclass (child), while the other classes are often referred to as parent classes. In JavaScript, you want to complete inheritance, assign instances of the parent class to subclasses, and then specializing the subclass (the child Class).

Tip: Because JavaScript does not detect the Prototype.constructor of subclasses (the stereotype's constructor), see core JavaScript 1.5 kernel reference: Global Objects:Object:prototype property, So we have to specify this value manually.

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 Code code as follows:

Defining the Person class
function person () {}
Person.prototype.walk = function () {
Alert (' I am walking! ');
};
Person.prototype.sayHello = function () {
Alert (' Hello ');
};
Defining the Student Class
function Student () {
Calling the parent class constructor
Person.call (this);
}
Inherit person
Student.prototype = new Person (); Fixed constructor pointer because it points to person
Student.prototype.constructor = Student; Replace SayHello method
Student.prototype.sayHello = function () {
Alert (' Hi, I am a student ');
}
Add Saygoodbye method
Student.prototype.sayGoodBye = function () {
Alert (' GoodBye ');
}
var student1 = new Student ();
Student1.sayhello ();
Student1.walk ();
Student1.saygoodbye (); Quarantine inheritance
Alert (student1 instanceof person); True
Alert (student1 instanceof Student); True


Packaging

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

Abstract

Abstraction is a mechanism (mechanism) that allows you to model the current part of a problem that is being handled. This can be done by inheriting (special) or combining (composition). JavaScript implements the special (specialization) through inheritance, by making the class instance a combination of property values for other objects.
The function class of JavaScript inherits from the object class (which illustrates the specificity of the model), and the Function.prototype property is an instance of object (this illustrates the combination).

Copy Code code as follows:
var foo = function () {};
Alert (' foo is a function: ' + (foo instanceof function));
Alert (' Foo.prototype is an object: ' + (Foo.prototype instanceof Object));

Polymorphic

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

Tips

The Object-oriented programming implementation technology presented in this paper is not only suitable for JavaScript, because it is very flexible for object-oriented programming.
Similarly, the techniques shown here neither use any language techniques (language hacks) nor emulate the object theory of other languages.
There are other, more advanced object-oriented programming techniques in JavaScript, but that 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.