Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Does javascript support object-oriented

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "whether javascript supports object-oriented". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

JavaScript supports object-oriented; object-oriented programming is a programming pattern that abstractly creates real-world models. Object-oriented uses previously established paradigms, including modularization, polymorphism, and encapsulation. Many popular programming languages, including JavaScript, support object-oriented programming.

The operating environment of this tutorial: windows10 system, javascript1.8.5 version, Dell G3 computer.

Javascript supports object-oriented

The core of JavaScript is to support object-oriented, and it also provides powerful and flexible OOP language capabilities. This article starts with an introduction to object-oriented programming, takes you to explore the object model of JavaScript, and finally describes some of the concepts of object-oriented programming in JavaScript.

Object oriented programming

Object-oriented programming is a programming mode that creates a real-world model in an abstract way. It uses previously established paradigms, including modularization, 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).

Relative to "a program is just a collection of functions, or a simple list of computer instructions." According to the traditional concept of software design, object-oriented programming can be regarded as software design that uses a series of objects to cooperate with each other. In OOP, each object can receive messages, process data, and send messages to other objects. Each object can be seen as a small independent machine with a clear role or responsibility.

The purpose of object-oriented programming is to promote better flexibility and maintainability in programming, which is widely popular in large-scale software engineering. With its emphasis on modularization, object-oriented code development is simpler and easier to understand. Compared with non-modular programming methods, it can analyze, code and understand complex situations and processes more directly.

Namespace

Namespaces allow developers to bundle all functional containers under a unique, application-related name.

Class class

Define the characteristics of the object. It is the template definition of the properties and methods of the object.

Object object

An instance of the.

Property attribute

The characteristics of an object, such as color.

Method method

The ability of an object, such as walking.

Constructor constructor

The called method at the moment of initialization of the object. Usually its name is the same as the class that contains it.

Inheritance inheritance

One class can inherit the characteristics of another class.

Encapsulation encapsulation

A method used to bind data to related methods.

Abstraction abstraction

Objects that combine complex inheritance, methods, and properties can simulate real-world models.

Polymorphism polymorphism

It means "many", and the state means "form". Different classes can define the same methods or properties.

Prototype programming

Prototype-based programming is not the style embodied in object-oriented programming, and behavior reuse (also known as inheritance in class-based languages) is achieved through the process of decorating its existing objects as prototypes. This pattern is also known as weak classing, prototyping, or instance-based programming.

The original (and most typical) prototype-based examples were developed by David Angel and Randall Smith. However, weakening programming styles have become increasingly popular recently and have been adopted by programming languages such as JavaScript,Cecil,NewtonScript,IO,MOO,REBOL,Kevo,Squeak (which uses frameworks to manipulate Morphic components), and several other programming languages.

JavaScript object-oriented programming

Namespace

A namespace is a container that allows developers to bundle all functionality under a unique, application-specific name. In JavaScript, a namespace is just another object that contains methods, properties, and objects.

Note: it is important to realize that, unlike other object-oriented programming languages, normal objects and namespaces in Javascript are no different at the language level. This may confuse beginners in JavaScript.

The idea behind the creation of the JavaScript namespace is simple: a global object is created and all variables, methods, and functions become properties of that object. The use of namespaces also minimizes the possibility of name conflicts in the application.

Let's create a global variable called MYAPP

/ / Global namespace var MYAPP = MYAPP | | {}

In the above code example, we first check to see if the MYAPP has been defined (in the same file or in another file). If so, use the existing MYAPP global object, otherwise, create an empty object called MYAPP to encapsulate methods, functions, variables, and objects.

We can also create subnamespaces:

/ / subnamespace MYAPP.event = {}

Here is the code for creating namespaces and adding variables, functions, and methods:

/ / create a container called MYAPP.commonMethod for common methods and properties MYAPP.commonMethod = {regExForName: ", / / define the regular verification of the name regExForPhone:", / / define the regular verification of the phone validateName: function (name) {/ / do something to the name name You can declare MYAPP.event = {addListener: function (el, type, fn) {/ / Code}, removeListener: function (el, type, fn) {/ / Code} by using the "this.regExForname" / / access regExForName variable}, validatePhoneNo: function (phoneNo) {/ / a pair of phone numbers}} / / object and method. GetEvent: function (e) {/ / Code} / / you can add other properties and methods} / / using the addListener method: MYAPP.event.addListener ("yourel", "type", callback)

Standard built-in object

JavaScript has several objects included at its core, such as Math,Object,Array and String objects. The following example demonstrates how to use the random () method of the Math object to get a random number.

Console.log (Math.random ())

Note: both here and the following examples assume that a method named console.log is globally defined. Console.log is not actually native to JavaScript.

Check out the JavaScript reference: global objects for a list of JavaScript built-in objects.

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

Custom object

Class

JavaScript is a prototype-based language that has no class declaration statements, such as those used in C + + or Java. This can sometimes be troublesome for programmers who are used to using classful declaration language. Instead, JavaScript can use methods as classes. Defining a class is as simple as defining a function. In the following example, we define a new class Person.

Function Person () {} / / or var Person = function () {}

Object (an instance of a class)

We use new obj to create a new instance of the object obj and assign the result (of type obj) to a variable for later call.

In the following example, we define a class named Person, and then we create two instances of Person (person1 and person2).

Function Person () {} var person1 = new Person (); var person2 = new Person ()

Note: there is a new instantiation method for creating uninitialized instances, please refer to Object.create.

Constructor

The constructor is called when it is instantiated (that is, when the object instance is created). A constructor is a method in an object. Functions can be used as constructors in JavaScript, so there is no need to specifically define a constructor method, and each declared function can be called and executed after instantiation.

Constructors are often used to assign values to the properties of an object or to prepare for a function call. Later in this article, it is described that methods in a class can be added either at definition or before use.

In the following example, the constructor calls an alert function when the Person class is instantiated.

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

Properties (object properties)

Properties are variables contained in a class; each object instance has several properties. For proper inheritance, the property should be defined in the prototype property (function) of the class.

You can use the keyword this to call properties in a class, where this is a reference to the current object. The syntax for accessing (reading / writing) its properties from the outside is: InstanceName.Property;, which is the same as the syntax in Java or many other languages (the syntax this.Property is often used for set and get property values in classes)

In the following example, we define a property firstName for defining the Person class and assign an initial value when instantiated.

Function Person (firstName) {this.firstName = firstName; alert ('Person instantiated');} var person1 = new Person (' Alice'); var person2 = new Person ('Bob'); / / Show the firstName properties of the objectsalert (' person1 is'+ person1.firstName); / / alerts "person1 is Alice" alert ('person2 is' + person2.firstName); / / alerts "person2 is Bob"

Method (object properties)

Methods are similar to properties, except that one is a function and the other can be defined as a function. Calling a method is much like accessing a property, except that add () is likely to take parameters after the method name. To define a method, you need to assign a function to the prototype property of the class; the name assigned to the function is used to call the object externally.

In the following example, we define the method sayHello () for the Person class and call it.

Function Person (firstName) {this.firstName = firstName;} Person.prototype.sayHello = function () {alert ("Hello, iTunm" + this.firstName);}; var person1 = new Person ("Alice"); var person2 = new Person ("Bob"); / / call the Person sayHello method.person1.sayHello (); / / alerts "Hello, iTunm Alice" person2.sayHello (); / / alerts "Hello, iTunm Bob"

In JavaScript, a method is usually a normal function bound to an object, which means that a method can be called outside of its context. Consider the code in the following example:

Function Person (firstName) {this.firstName = firstName;} Person.prototype.sayHello = function () {alert ("Hello, iTunm" + this.firstName);}; var person1 = new Person ("Alice"); var person2 = new Person ("Bob"); var helloFunction = person1.sayHello; person1.sayHello (); / / alerts "Hello, iTunm Alice" person2.sayHello () / / alerts "Hello, Isimm Bob" helloFunction (); / / alerts "Hello, Ilemm undefined" (or fails with a TypeError in strict mode) console.log (helloFunction = person1.sayHello); / / logs trueconsole.log (helloFunction = Person.prototype.sayHello); / / logs truehelloFunction.call (person1) / / logs "Hello, iTunm Alice"

As shown in the example above, all references to sayHello functions, including person1, Person.prototype, and helloFunction, refer to the same function.

In the process of calling a function, the value of this depends on how we call the function. Normally, we call the function through an expression person1.sayHello (): that is, we get the called function from the properties of an object. At this point, this is set to the object from which we get the function (that is, person1). This is why person1.sayHello () uses the name "Alice" and person2.sayHello () uses the name "bob".

However, when we use different calling methods, the value of this is different. When called from the variable helloFunction (), this is set to the global object (that is, window in the browser). Since the object (most likely) has no firstName attribute, the result we get is "Hello, Ihumm undefined". (this is the result of loose mode, and in strict mode, the result will be different (at this point an error will be generated). But to avoid confusion, we won't go into details here. In addition, we can use Function#call (or Function#apply) to explicitly set the value of this as we did at the end of the example above.

Please refer to Function#call and Function#apply for more information

Inherit

The way to create a specialized version of a class or classes is called inheritance (Javascript only supports single inheritance). The specialized version of the class created is usually called the subclass, and the other class is usually called the parent class. In Javascript, inheritance is achieved by giving a subclass an instance of the parent class and specializing the subclass. In modern browsers you can use Object.create to implement inheritance.

JavaScript does not detect the prototype.constructor of the subclass (see Object.prototype), so we must declare it manually.

In the following example, we define the Student class as a subclass of the Person class. Then we redefine the sayHello () method and add the sayGoodBye () method.

/ / define Person constructor function Person (firstName) {this.firstName = firstName;} / / add the method Person.prototype.walk = function () {alert ("I am walking!");}; Person.prototype.sayHello = function () {alert ("Hello, Isimm" + this.firstName);} / / define the Student constructor function Student (firstName, subject) {/ / call the parent constructor to ensure (using Function#call) "this" to set the correct Person.call (this, firstName) during the call; / / initialize the Student class-specific attribute this.subject = subject;} / / create a Student.prototype object inherited from Person.prototype. / / Note: the common mistake is to use "new Person ()" to establish Student.prototype.//. There are many mistakes in this. The most important point is that when we instantiate / / we cannot give any FirstName parameter / / call Person to the Person class in the correct position as follows We call it from Student Student.prototype = Object.create (Person.prototype) / / See note below / / set the "constructor" attribute to point to StudentStudent.prototype.constructor = Student; / / change the "sayHello" method Student.prototype.sayHello = function () {console.log ("Hello, Isimm" + this.firstName + ". Ichimm studying "+ this.subject +".);}; / add "sayGoodBye" method Student.prototype.sayGoodBye = function () {console.log ("Goodbye!");}; / / Test example: var student1 = new Student ("Janet", "Applied Physics"); student1.sayHello (); / / "Hello, iTunm Janet. I'm studying Applied Physics. "student1.walk (); / /" I am walking! "student1.sayGoodBye (); / /" Goodbye! "/ / Check that instanceof works correctlyconsole.log (student1 instanceof Person); / / trueconsole.log (student1 instanceof Student); / / true

For the line "Student.prototype = Object.create (Person.prototype);", in the old JavaScript engine that does not support the Object.create method, you can use a "polyfill" (also known as "shim", see the article link), or a function to get the same return value, as follows:

Function createObject (proto) {function ctor () {} ctor.prototype = proto; return new ctor ();} / / Usage:Student.prototype = createObject (Person.prototype)

For more information, please refer to Object.create, and there is also an old JavaScript engine compatibility scheme (shim) in the connection.

Encapsulation

In the previous example, the study class 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, and for all methods that inherit from the parent class, you only need to define the ones you want to change in the subclass.

Abstract

Abstraction is a mechanism that allows you to simulate a common part of a work problem. This can be achieved through inheritance (materialization) or combination.

JavaScript materializes through inheritance and composition by allowing instances of the class to be property values of other objects.

The JavaScript Function class inherits from the Object class (this is a typical materialization). The property of Function.prototype is an Object instance (this is a typical combination).

Var foo = function () {}; console.log ('foo is a Function:' + (foo instanceof Function)); / / logs "foo is a Function: true" console.log ('foo.prototype is an Object:' + (foo.prototype instanceof Object)); / / logs "foo.prototype is an Object: true"

Polymorphisms

As with all methods and properties defined within prototype properties, different classes can define methods with the same name; methods act on the class in which they are located. And this is true only if two classes are not parented (in the inheritance chain, one class does not inherit from other classes).

This is the end of the content of "whether javascript supports object-oriented". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report