Home > Web Front-end > JS Tutorial > body text

Introduction to JavaScript Object-Oriented Programming Tutorial_Basic Knowledge

WBOY
Release: 2016-05-16 16:52:19
Original
1414 people have browsed it

Although there are differences between object-oriented JavaScript and other languages, which have triggered some debates, there is no doubt that JavaScript has powerful object-oriented programming capabilities

This article starts with an introduction to object-oriented programming Begins, then reviews the JavaScript object model, and finally demonstrates object-oriented programming concepts in JavaScript.

JavaScript Review

If you feel unsure about JavaScript concepts such as variables, types, functions, and scopes, you can read Reintroducing these topics in JavaScript. You can also check out JavaScript 1.5 Core Guide

Object-Oriented Programming

Object-oriented programming is a programming paradigm that uses abstractions to create models based on the real world. It uses several previously established paradigm techniques, 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 collections of collaborating objects to design software, contrary to the traditional view of programs as collections of functions, or reduced to lists of computer instructions. In object-oriented programming, each object has the following capabilities: receive messages, process data, and send messages to other objects. Each object can be viewed as an independent little machine with different roles or responsibilities.
Object-oriented programming aims to promote greater flexibility and maintainability in programming, and is widely popular in large-scale software engineering. Because of its emphasis on modularity, object-oriented code is designed to make development simpler, easier to understand later, and makes it easier to analyze, code, and understand complex situations and steps than less modular programming methods. direct.

Special terms

Class
~ Defines the characteristics of the object.
Object
~ Instance of class.
Property
~ Characteristic of an object, such as color.
Method
~ Some object ability, such as walking.
Constructor
~ Method called during instantiation.
Inheritance
~ A class can inherit characteristics from another class.
Encapsulation
~ A class only defines the characteristics of the object, and a method only defines how the method is executed.
Abstraction
~ Combines complex inheritance, methods, and properties of an object, and must be able to simulate a certain reality model.
Polymorphism
~ Different classes may define the same methods or properties.
For a further description of object-oriented programming, see the Wikipedia entry on object-oriented programming.

Prototype-based programming

Prototype-based programming is an object-oriented programming style in which classes do not exist and behavior reuse (called inheritance in class-based languages) is disguised as a prototype This is done using existing objects. This pattern is also called class-less, prototype-oriented, or instance-based programming.
The original (and very canonical) example of a prototype-based language is the Self programming language developed by David Ungar and Randall Smith. However, this style of classless programming has become increasingly popular recently and has been adopted by several programming languages ​​such as JavaScript, Cecil, NewtonScript, Io, MOO, REBOL, Kevo, Squeak (when using the Viewer framework to manipulate Morphic components) , and several other languages.

JavaScript Object-Oriented Programming

Core Objects

JavaScript has several objects included in its core; for example, Math, Object, Array, and String objects. The following example demonstrates how to obtain a random number using the random() method of the Math object.

Copy code The code is as follows:

alert(Math.random());

Tip: This and all other examples assume that the function name alert has been defined globally (as alert is included in web browsers). The alert function is not actually part of JavaScript itself.

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

Every object in JavaScript is an instance of an Object object and therefore inherits all its properties and methods.

Custom Objects

The Class

JavaScript is a prototype-based language that does not contain class statements like those found in C or Java. This can sometimes confuse programmers who are used to languages ​​with a class statement. However, JavaScript uses functions as classes. Defining a class is as simple as defining a function. In the following example, we define a new class called Person.

Copy code The code is as follows:
function Person() { }


The Object (Class Instance)

To create a new instance of the obj object, we use the statement new obj and assign the result (its type is obj) Give it a variable so it can be accessed later.
In the following example, we first define a class named Person and then create two instances (person1 and person2).
Copy code The code is as follows:
function Person() {}
var person1 = new Person( );
var person2 = new Person();

Also see the new instantiation alternative Object.create.

The Constructor

The constructor is called when instantiated (the moment an object instance is created). A constructor is a method of a class. In JavaScript, a function is used as the constructor of the object; therefore, there is no need to explicitly define a constructor method. Every behavior declared in a class is executed when it is instantiated.

The constructor is used to set object properties or call methods to prepare for use of the object. Later in this article, you'll learn how to add class methods and their definitions using a different syntax.

In the following example, when a Person is instantiated, the constructor of the Person class displays an alert box.

Copy code The code is as follows:
function Person() {
alert('Person instantiated');
}
var person1 = new Person();
var person2 = new Person();

The Property (object attribute)

Properties are variables contained within a class; each object instance has these properties. Properties should be set in the prototype attribute of the class (function) in order for inheritance to work properly.
Manipulating attributes in a class is achieved through the this keyword, which refers to the current object. Accessing (reading or writing) a property from outside a class is through the following syntax: InstanceName.Property; this is the same syntax used in C, Java, and some other languages. (Use this.Property syntax inside the class to get or set the property value).

In the following example, we define the gender attribute for the Person class and then define the attribute during initialization.

Copy code The 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: 女
//Display person1’s gender
alert('person1 is a ' person1.gender); // person1 is a Male

The methods

Methods follow the same logic as properties; the difference is that they are functions and are defined as functions. Calling a method is similar to accessing a property, but you add () to the end of the method name, which may have arguments. To define a method is to assign a function to a named attribute on the prototype attribute of the class; the name assigned to the function is the name under which the method is called on the object.
In the following example, we define and use the sayHello() method for the Person class.

Copy code The 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 Person's sayHello method.
person1.sayHello(); // hello

In JavaScript, methods are ordinary function objects that are bound to a class/object as properties, which means that they can be called "out of the context". Consider the following sample code:

Copy the code The 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 once. This shows that there are no "per-object methods" in JavaScript, because all references to the method point to the exact same function, the one we originally defined on the prototype. When a function is called as a method (or property to be precise), JavaScript "binds" the current "object context" to the specific "this" variable. This is equivalent to calling the "call" method of the function object, as follows:
Copy the code The code is as follows:

genderTeller.call(person1); //alerts 'Male'e

For more information, see Function.call and Function.apply

Inheritance

Inheritance is a method for creating a class that is a specialized version of one or more classes. (JavaScript only supports single-class inheritance). This specialized class is often called the child, and the other classes are often called the parent. In JavaScript, to complete inheritance, you need to assign an instance of the parent class to the subclass, and then specialize the subclass.

Tip: Since JavaScript does not detect the prototype.constructor (prototype's constructor) of a subclass, see 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 code The 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 Student class
function Student() {
// Call the parent class constructor
Person.call(this);
}
// Inherit Person
Student.prototype = new Person(); // Correct 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 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


Packaging

In the above example, Student does not need to know how the walk() method of the Person class is implemented, but it can still use this method; the Student class does not need to explicitly define this method unless we want to change it. This is called encapsulation, whereby each class inherits the methods of its parent class and only defines what it wishes to change.

Abstract

Abstraction is a mechanism that allows modeling of the current part of the problem being addressed. This can be achieved through inheritance (specialization) or composition. JavaScript achieves specialization through inheritance and composition by letting class instances become property values ​​of other objects.
JavaScript's Function class inherits from the Object class (this illustrates specialization of the model), and the Function.prototype property is an instance of Object (this illustrates composition).

Copy code The code is 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 like all methods and properties are defined inside prototype attributes, different classes can define methods with the same name; the scope of methods is limited to the class in which they are defined. This is only true when there is no parent-child relationship between the two classes (when one class does not inherit from other classes in the inheritance chain).

Tips

The object-oriented programming implementation techniques presented in this article are not only applicable to JavaScript, because it is very flexible in terms of how to do object-oriented programming.
Again, the techniques presented here neither use any language hacks nor imitate object theory implementations in other languages.
There are other more advanced object-oriented programming techniques in JavaScript, but those are beyond the scope of this introductory article.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template