search
HomeWeb Front-endJS TutorialJavaScript object-oriented programming basics_basic knowledge

Re-understand object-oriented
In order to illustrate that JavaScript is a completely object-oriented language, it is first necessary to start with the concept of object-oriented and discuss several concepts in object-oriented:

  1. Everything is an object
  2. Objects have encapsulation and inheritance features
  3. Objects use messages to communicate with each other, and each has information hiding

Based on these three points, C is a semi-object-oriented and semi-procedural language, because although it implements class encapsulation, inheritance and polymorphism, there are non-object global functions and variables. Java and C# are completely object-oriented languages. They organize functions and variables in the form of classes so that they cannot exist without objects. But here the function itself is a process, just attached to a certain class.

However, object-oriented is just a concept or programming idea, and it should not depend on a certain language for its existence. For example, Java uses object-oriented thinking to construct its language, and it implements mechanisms such as classes, inheritance, derivation, polymorphism, and interfaces. However, these mechanisms are only a means to implement object-oriented programming, not necessary. In other words, a language can choose an appropriate way to implement object orientation based on its own characteristics. Therefore, since most programmers first learn or use high-level compiled languages ​​such as Java and C (although Java is semi-compiled and semi-interpreted, it is generally explained as a compiled language), they preconceivedly accept the term "class". Object-oriented implementation method, so when learning scripting languages, it is customary to use the concepts in class-based object-oriented languages ​​to judge whether the language is an object-oriented language or whether it has object-oriented characteristics. This is also one of the important reasons that hinders programmers from learning and mastering JavaScript in depth.
In fact, the JavaScript language implements object-oriented programming through a method called prototype. Let's discuss the differences between the two methods of constructing the objective world, class-based object-oriented and prototype-based object-oriented.
Comparison between class-based object-oriented and prototype-based object-oriented approaches
In the class-based object-oriented approach, objects are generated based on classes. In the prototype-based object-oriented approach, objects are constructed using constructors and prototypes. Give an example from the objective world to illustrate the difference between the two ways of cognition. For example, when a factory builds a car, on the one hand, workers must refer to an engineering drawing and the design stipulates how the car should be manufactured. The engineering drawings here are like classes in language, and cars are manufactured according to this class; on the other hand, workers and machines (equivalent to constructors) use various parts such as engines, tires, The steering wheel (equivalent to each attribute of the prototype) constructs the car.
In fact, there is still debate about which of the two methods expresses object-oriented ideas more thoroughly. But the author believes that prototype object-oriented is a more thorough object-oriented approach for the following reasons:
First of all, the creation of objects in the objective world is the result of the construction of other physical objects, and abstract "drawings" cannot produce "cars". In other words, a class is an abstract concept rather than an entity, and the creation of objects is The creation of an entity;
Secondly, according to the most basic object-oriented rule that everything is an object, the class itself is not an object. However, the constructor and prototype in the prototype method are themselves other objects through the prototype method. Constructed object.
Thirdly, in a class-based object-oriented language, the state of an object is held by the object instance, and the behavior method of the object is held by the class that declares the object, and only the structure and Methods can be inherited; in prototype object-oriented languages, the behavior and status of the object belong to the object itself and can be inherited together (reference resources), which is closer to objective reality.
Finally, class-based object-oriented languages ​​such as Java allow static properties and static methods to be declared in classes in order to make up for the inconvenience of not being able to use global functions and variables in procedural languages. In fact, there is no so-called static concept in the objective world, because everything is an object! In a prototype object-oriented language, except for built-in objects, global objects, methods or properties are not allowed to exist, and there is no static concept. All language elements (primitives) must depend on objects for their existence. However, due to the characteristics of functional languages, the objects on which language elements depend change with changes in the runtime context, which is specifically reflected in changes in the this pointer. It is this characteristic that is closer to the natural view that "everything belongs to something, and the universe is the foundation for the survival of all things."


JavaScript object-oriented basic knowledge

Although JavaScript itself does not have the concept of classes, it still has object-oriented characteristics, although it is different from common object-oriented languages.

The simple way to create an object is as follows:

function myObject() {

};

JavaScript 中创建对象的方法一般来说有两种:函数构造法和字面量法,上面这种属函数构造法。下面是一个字面量法的例子:

var myObject = {

};

If you only need one object and do not need other instances of the object, it is recommended to use the literal method. If multiple instances of an object are required, the function constructor is recommended.
Define properties and methods

Function construction method:

function myObject() {
 this.iAm = 'an object';

 this.whatAmI = function() {
 console.log('I am ' + this.iAm);
 };
};

Literal method:

var myObject = {
 iAm : 'an object',

 whatAmI : function() {
 console.log('I am ' + this.iAm);
 }
};

The objects created by the above two methods have a property named "iAm" and a method named "whatAmI". Properties are variables in an object, and methods are functions in an object.

How to get attributes and call methods:

var w = myObject.iAm;

myObject.whatAmI();

When calling a method, you must add parentheses after it. If you do not add parentheses, then it will just return a reference to the method.
The difference between the two methods of creating objects

  • When defining properties and methods in the function constructor, you must use the prefix this, which is not required in the literal method.
  • The function constructor uses = when assigning values ​​to properties and methods, and the literal method uses : .
  • If there are multiple properties or methods, they should be separated by ; in the function constructor and by , in the literal method.

For objects created by literal method, you can directly call its properties or methods using the reference of the object:

myObject.whatAmI();

For the function constructor, you need to create an instance of the object before you can call its properties or methods:

var myNewObject = new myObject();
myNewObject.whatAmI();

Use constructor

Now let’s return to the previous function construction method:

function myObject() {
 this.iAm = 'an object';
 this.whatAmI = function() {
 console.log('I am ' + this.iAm);
 };
};

Actually, it looks like a function. Since it is a function, can I pass parameters to it? Modify the code slightly:

function myObject(what) {
 this.iAm = what;
 this.whatAmI = function(language) {
 console.log('I am ' + this.iAm + ' of the ' + language + ' language');
 };
};

Then instantiate the object and pass in the parameters:

var myNewObject = new myObject('an object');
myNewObject.whatAmI('JavaScript');

The final output of the program is I am an object of the JavaScript language.
There are two ways to create objects, which one should I use?

For literal methods, because it does not require instantiation, if the value of an object is modified, the value of the object is permanently modified, and any other access will be the modified value. . For the function constructor, when modifying the value, the value of its instance is modified. It can instantiate N objects, and each object can have its own different value without interfering with each other. Compare the following code snippets.

Let’s look at the literal method first:

var myObjectLiteral = {
 myProperty : 'this is a property'
};

console.log(myObjectLiteral.myProperty); // log 'this is a property'

myObjectLiteral.myProperty = 'this is a new property';

console.log(myObjectLiteral.myProperty); // log 'this is a new property'

Even if a new variable is created to point to this object, the result is still the same:

var myObjectLiteral = {
 myProperty : 'this is a property'
};

console.log(myObjectLiteral.myProperty); // log 'this is a property'

var sameObject = myObjectLiteral;

myObjectLiteral.myProperty = 'this is a new property';

console.log(sameObject.myProperty); // log 'this is a new property'

Look at the function construction method again:

// 用函数构造法
var myObjectConstructor = function() {
   this.myProperty = 'this is a property'
};

// 实例化一个对象
var constructorOne = new myObjectConstructor();

// 实例化第二个对象
var constructorTwo = new myObjectConstructor();

// 输出
console.log(constructorOne.myProperty); // log 'this is a property'

// 输出
console.log(constructorTwo.myProperty); // log 'this is a property'

和预期一样,两个对象的属性值是一样的。如果修个其中一个对象的值呢?

// 用函数构造法
var myObjectConstructor = function() {
 this.myProperty = 'this is a property';
};

// 实例化一个对象
var constructorOne = new myObjectConstructor();

// 修改对象的属性
constructorOne.myProperty = 'this is a new property';

// 实例化第二个对象
var constructorTwo = new myObjectConstructor();

// 输出
alert(constructorOne.myProperty); // log 'this is a new property'

// 输出
alert(constructorTwo.myProperty); // log 'this is a property'

As you can see, different objects instantiated using the function constructor are independent of each other and can each have different values. Therefore, which method to use to create objects depends on the actual situation.

Statement
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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),