


Introduction to JavaScript Object-Oriented Programming Tutorial_Basic Knowledge
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.
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.
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).
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.
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.
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.
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:
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:
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.
// 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).
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Concise and easy-to-understand MyBatis introductory tutorial: write your first program step by step MyBatis is a popular Java persistence layer framework that simplifies the process of interacting with databases. This tutorial will show you how to use MyBatis to create and perform simple database operations. Step 1: Environment setup First, make sure your Java development environment has been installed. Then, download the latest version of MyBatis and add it to your Java project. You can download it from the official website of MyBatis

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

Overview of how to use WebSocket and JavaScript to implement an online electronic signature system: With the advent of the digital age, electronic signatures are widely used in various industries to replace traditional paper signatures. As a full-duplex communication protocol, WebSocket can perform real-time two-way data transmission with the server. Combined with JavaScript, an online electronic signature system can be implemented. This article will introduce how to use WebSocket and JavaScript to develop a simple online
