Introduction to JavaScript object oriented programming

  • 2020-03-30 02:38:08
  • OfStack

While there has been some debate about the differences between object-oriented JavaScript and other languages, there is no doubt that JavaScript has powerful object-oriented programming capabilities

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

JavaScript to review

If you're confused about JavaScript concepts like variables, types, functions, and scopes, you can read and reintroduce these topics in JavaScript. You can also consult (link: https://developer.mozilla.org/en/JavaScript/Guide)
Object oriented programming

Special terms

Class (Class)
~ define characteristics of the object.
Object (Object)
Instance of the ~ class.
Property
A characteristic of an object, such as color.
Method Method
Some object ability, such as walking.
Constructor
Method called when ~ instantiation.
Inheritance
A class can inherit characteristics from another class.
Encapsulation (Encapsulation)
A class defines only the characteristics of the object, and a method defines only how the method is executed.
Abstraction
~ combines the complex inheritance, methods, and properties of an object and must be able to simulate a realistic model.
Polymorphism
~ different classes may define the same method or attribute.
For a further description of object-oriented programming, see the wikipedia entry for object-oriented programming.

Prototype-based programming

Prototype-based programming is an object-oriented programming style in which classes do not exist, and behavioral reuse (called inheritance in class-based languages) is accomplished by whitewashing existing objects that act as prototypes. This pattern is also known as class-less, prototype-oriented, or instance-based programming.
The first (and very canonical) example of a prototype-based language was the Self programming language developed by David Ungar and Randall Smith. However, this category-free programming style has gained popularity recently and has been adopted by programming languages such as avaScript, Cecil, NewtonScript, Io, MOO, REBOL, Kevo, Squeak (when using the Viewer frame to manipulate Morphic components), and several others.

JavaScript object-oriented programming

Core Objects

JavaScript has several objects contained in its core; For example, objects like Math, Object, Array, and String. The following example demonstrates how to use the random() method of the Math object to get a random number.


alert(Math.random());

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

JavaScript core object list, see (link: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects)
Each Object in JavaScript is an instance of an Object, and therefore inherits all its properties and methods.

Custom Objects

Class (The Class)

JavaScript is a prototype-based language that does not contain class statements that can be found in, say, C++ or Java. This can sometimes confuse programmers 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 named Person.

function Person() { }


The Object (Class Instance)

To create a new instance of an obj object, we use the statement new obj and assign the result (of type obj) to a variable for later access.
In the following example, we first define a class named Person and then create two instances (person1 and person2).
function Person() {}
var person1 = new Person();
var person2 = new Person();

Alternative methods may also refer to the new instantiation (link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create).

The Constructor

The constructor is called when instantiated (the instant an object instance is created). A constructor is a method of a class. In JavaScript, the function is used as the constructor of the object. Therefore, there is no need to explicitly define a constructor method. Each behavior declared in a class is executed at instantiation.

The constructor is used to set an object's properties or to call methods to prepare it for use. Later in this article, you can add class methods and their definitions by using a different syntax.

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

function Person() {
    alert('Person instantiated');
}
var person1 = new Person();
var person2 = new Person();

The Property (object attribute)

Properties are variables contained in a class; Each object instance has these properties. Properties should be set in the prototype properties of a class (function) so that inheritance works properly.
Manipulating properties in a class is done through the this keyword, which refers to the current object. To access (read or write) an attribute outside the class, use the following syntax: instancename.property; This is the same syntax used in C++, Java, and some other languages. Use the syntax of this.property 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 that attribute at initialization time.

function Person(gender) {
    this.gender = gender;
    alert('Person instantiated');
}
var person1 = new Person('Male'); //Male: Male
var person2 = new Person('Female'); //Female: Female
//Displays the gender of the person1
alert('person1 is a ' + person1.gender); // person1 is a Male

(The methods)

Methods follow the same logic as attributes; The difference is that they are functions and are defined as functions. Calling a method is similar to accessing a property, except you add () at the end of the method name, which may have arguments. Define a method that specifies a function for a named property on the prototype property of this class. The name to which the function is assigned is the name by which the method is 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, methods are normal function objects bound to a class/object as properties, which means they 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 once. This shows that there is no "per-object methods" in JavaScript, because all references to that method point to the exact same function that we originally defined on the prototype. When a function is called as a method (or rather as a property), JavaScript "binds" the current "object context" to a specific "this" variable. This is equivalent to calling the "call" method of the function object, as follows:

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

More information, please refer to the (link: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call) and (link: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply)

Inheritance

Tip: because JavaScript is not a subclass of the prototype. The constructor (prototype constructor), refer to the attributes (link: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/prototype), so we have to manually specify the 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 superclass constructor
    Person.call(this);
}
//Inherit the Person
Student.prototype = new Person(); //Fixed 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(); //Inspection inheritance
alert(student1 instanceof Person); // true
alert(student1 instanceof Student); // true


encapsulation

abstract

Abstraction is a mechanism that allows the current part of the problem being addressed to be modeled. This can be done by inheritance (specialization) or composition. JavaScript through inheritance to realize specialization (specialization), through making class instance attribute value to realize the combination of other objects.
JavaScript's Function class inherits from the Object class (which illustrates the specialization of the model), and the function.prototype property is an instance of Object (which illustrates the composition).

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 properties are defined within the stereotype property, different classes can define methods with the same name; Methods are scoped within the class in which they are defined. This is true only if there is no parent-child relationship between the two classes (when a class does not inherit from other classes in the inheritance chain).

prompt

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


Related articles: