search
HomeWeb Front-endJS TutorialJavaScript object-oriented knowledge collection (Read JavaScript Advanced Programming (Third Edition))_javascript skills

The first time I swallowed it wholeheartedly, I didn't ask for a clear explanation, and I suddenly felt enlightened. However, when I went to bed at night, I found many problems and didn't understand anything. After reading it a second time, I found that it was like this. After using it for a few days, I found that I was still relying on memory when writing by hand, so the next time, the next time...

It is unreliable to figure out things by memory alone, and my mind will go blank after a long time. Especially many technical ideas and principles, if you just don’t practice them, even if you think about them very clearly at the time, you will forget them after a long time. Furthermore, some things on the Internet can only be said to provide a convenient way to view them. It is better to summarize them yourself afterwards. After all, most of them are personal summaries. Some concepts are difficult to explain clearly, and two people are talking about the same thing. , generally speaking, the steps and chapters are different, so it is easy to form cross memories. The more cross memories, the more confusing it will be. It's better to look at things with a skeptical attitude. Try it out and you'll know what it's like. Books with guaranteed high quality or official stuff are good sources.

While you can still see clearly now and your mind is still clear, record it and make a memo. The conceptual stuff is in the book to reduce misunderstanding in the future. Write the example by hand and verify it, and then draw a picture so that you can understand it at a glance later.

1. Encapsulation

Object definition: ECMA-262 defines an object as: "a collection of unordered attributes, where attributes can include basic values, objects or functions" .

Create objects: Each object is created based on a reference type. This reference type can be a native type (Object, Array, Date, RegExp, Function, Boolean, Number, String) or a self- Define type.

1. Constructor pattern

Copy code The code is as follows:

function Person(name, age) {
this.name = name;
this.age = age;
this.sayName = function() {
alert(this.name);
}
}
Object instances can be created using the new operator through the above constructor.
var zhangsan = new Person('zhangsan', 20);
var lisi = new Person('lisi', 20);
zhangsan.sayName();//zhangsan
lisi.sayName (); //lisi

Creating an object through new goes through 4 steps

1. Create a new object; [var o = new Object();]

2. Assign the scope of the constructor to the new object (so this points to the new object); [Person.apply(o)] [Person’s original this points to window]

3. Execute the code in the constructor (add attributes to this new object);

4. Return the new object.

Steps to restore new through code:
Copy code The code is as follows:

function createPerson(P) {
var o = new Object();
var args = Array.prototype.slice.call(arguments, 1);
o.__proto__ = P.prototype;
P.prototype.constructor = P;
P.apply(o, args);
}
Test the new create instance method
var wangwu = createPerson(Person, 'wangwu', 20) ;
wangwu.sayName();//wangwu


2. Prototype mode

Prototype object concept: Whenever you create a new function, A prototype attribute is created for the function according to a specific set of rules. This attribute points to the prototype object of the function. By default, all prototype objects automatically get a constructor property, which contains a pointer to the function where the prototype property is located. Through this constructor, you can continue to add other properties and methods to the prototype object. After creating a custom constructor, its prototype object will only obtain the constructor property by default; as for other methods, they are inherited from Object. When a constructor is called to create a new instance, the instance will contain a pointer (internal property) that points to the prototype object of the constructor. ECMA-262 5th Edition calls this pointer [[Prototype]]. There is no standard way to access [[Prototype]] in scripts, but Firefox, Safari, and Chrome support an attribute __proto__ on every object; in other implementations, this attribute is completely invisible to scripts. The really important point to make clear, though, is that the connection exists between the instance and the constructor's prototype object, not between the instance and the constructor.

This paragraph basically outlines the relationship between constructors, prototypes, and examples. The following figure shows it more clearly
JavaScript object-oriented knowledge collection (Read JavaScript Advanced Programming (Third Edition))_javascript skills
Copy Code The code is as follows:

function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.country = 'chinese';
Person.prototype.sayCountry = function() {
alert(this.country);
}

var zhangsan = new Person('zhangsan', 20);
var lisi = new Person('lisi', 20);

zhangsan.sayCountry(); //chinese
lisi.sayCountry(); //chinese

alert(zhangsan.sayCountry = = lisi.sayCountry); //true

Note: The prototype object of the constructor is mainly used to allow multiple object instances to share the properties and methods it contains. But this is also where problems tend to occur. If the prototype object contains a reference type, then the reference type stores a pointer, so value sharing will occur. As follows:
Copy code The code is as follows:

Person.prototype.friends = ['wangwu' ]; //Person adds an array type
zhangsan.friends.push('zhaoliu'); //Zhang San’s modification will affect Li Si
alert(zhangsan.friends); //wangwu,zhaoliu
alert(lisi.friends); //wangwu, zhaoliu Li Si also has one more

3. Use the constructor mode and prototype mode in combination

This mode is to use The most widespread and recognized way to create custom types. Constructor pattern is used to define instance properties, while prototype pattern is used to define methods and shared properties. In this way, each instance has its own copy of the instance attributes and shares references to methods, which saves memory to the maximum extent.

The modified prototype mode is as follows:
Copy the code The code is as follows:

function Person(name, age) {
this.name = name;
this.age = age;
this.friends = ['wangwu'];
}

Person.prototype.country = 'chinese';
Person.prototype.sayCountry = function() {
alert(this.country);
}

var zhangsan = new Person(' zhangsan', 20);
var lisi = new Person('lisi', 20);

zhangsan.friends.push('zhaoliu');
alert(zhangsan.friends); / /wangwu,zhaoliu
alert(lisi.friends); //wangwu

2. Inheritance

Basic concepts of inheritance

ECMAScript mainly relies on the prototype chain Implement inheritance (you can also inherit by copying properties).

The basic idea of ​​the prototype chain is to use prototypes to let one reference type inherit the properties and methods of another reference type. The relationship between constructors, prototypes, and examples is: each constructor has a prototype object, the prototype object contains a pointer to the constructor, and the instance contains an internal pointer to the prototype. So, by making the prototype object equal to an instance of another type, the prototype object will contain a pointer to the other prototype, and accordingly, the other prototype will also contain this pointer to the other constructor. If another prototype is an instance of another type, then the above relationship still holds, and so on, layer by layer, a chain of instances and prototypes is formed. This is the basic concept of the prototype chain.

It is confusing to read and difficult to understand. Verify directly through examples.

1. Prototype chain inheritance
Copy code The code is as follows:

function Parent() {
this.pname = 'parent';
}
Parent.prototype.getParentName = function() {
return this.pname;
}

function Child() {
this.cname = 'child';
}
//The child constructor prototype is set to an instance of the parent constructor, forming a prototype chain so that Child has the getParentName method
Child .prototype = new Parent();
Child.prototype.getChildName = function() {
return this.cname;
}

var c = new Child();
alert(c.getParentName()); //parent

Illustration:
JavaScript object-oriented knowledge collection (Read JavaScript Advanced Programming (Third Edition))_javascript skills

Prototype chain problem, if the parent class includes a reference type, Child.prototype = new Parent() will bring the reference type in the parent class to In the prototype of a subclass, prototype properties of reference type values ​​will be shared by all instances. The problem comes back to section [1, 2].

2. Combination inheritance - the most commonly used inheritance method

Combination inheritance is a combination of prototype chain and borrowed constructor (apply, call) technologies. The idea is to use the prototype chain to achieve inheritance of prototype properties and methods, and to achieve inheritance of instance properties by borrowing constructors. In this way, methods can be defined on the prototype to achieve function reuse, and each instance can be guaranteed to have its own attributes.
Copy code The code is as follows:

function Parent(name) {
this.name = name;
this.colors = ['red', 'yellow'];
}
Parent.prototype.sayName = function() {
alert(this.name);
}

function Child(name, age) {
Parent.call(this, name); //Call Parent() for the second time
this.age = age;
}

Child.prototype = new Parent(); //The first time Parent() is called, the properties of the parent class will be
Child.prototype.sayAge = function() {
alert(this.age );
}

var c1 = new Child('zhangsan', 20);
var c2 = new Child('lisi', 21);
c1.colors.push( 'blue');
alert(c1.colors); //red,yellow,blue
c1.sayName(); //zhangsan
c1.sayAge(); //20

alert(c2.colors); //red,yellow
c2.sayName(); //lisi
c2.sayAge(); //21

combination inheritance The problem is that the supertype constructor is called twice each time: once when creating the subtype prototype, and once inside the subtype constructor. This will cause the rewriting of attributes. The subtype constructor contains the attributes of the parent class, and the prototype object of the subclass also contains the attributes of the parent class.

3. Parasitic combination inheritance - the most perfect inheritance method

The so-called parasitic combination inheritance means inheriting properties by borrowing constructors and inheriting methods through the hybrid form of the prototype chain. The basic idea behind it is: instead of calling the supertype's constructor to specify the prototype of the subclass, all we need is a copy of the supertype's prototype
copy Code The code is as follows:

function extend(child, parent) {
var F = function(){}; //Define an empty constructor
F.prototype = parent.prototype; //Set as the prototype of the parent class
child.prototype = new F(); //Set the prototype of the subclass as an instance of F, forming a prototype chain
child .prototype.constructor = child; //Reassign the subclass constructor pointer
}

function Parent(name) {
this.name = name;
this.colors = [' red', 'yellow'];
}
Parent.prototype.sayName = function() {
alert(this.name);
}

function Child(name, age) {
Parent.call(this, name);
this.age = age;
}

extend(Child, Parent); //Implement inheritance
Child. prototype.sayAge = function() {
alert(this.age);
}

var c1 = new Child('zhangsan', 20);
var c2 = new Child( 'lisi', 21);

c1.colors.push('blue');
alert(c1.colors); //red,yellow,blue
c1.sayName(); //zhangsan
c1.sayAge(); //20
alert(c2.colors); //red,yellow
c2.sayName(); //lisi
c2.sayAge() ; //21
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
如何使用Go语言实现面向对象的事件驱动编程如何使用Go语言实现面向对象的事件驱动编程Jul 20, 2023 pm 10:36 PM

如何使用Go语言实现面向对象的事件驱动编程引言:面向对象的编程范式被广泛应用于软件开发中,而事件驱动编程是一种常见的编程模式,它通过事件的触发和处理来实现程序的流程控制。本文将介绍如何使用Go语言实现面向对象的事件驱动编程,并提供代码示例。一、事件驱动编程的概念事件驱动编程是一种基于事件和消息的编程模式,它将程序的流程控制转移到事件的触发和处理上。在事件驱动

解析PHP面向对象编程中的享元模式解析PHP面向对象编程中的享元模式Aug 14, 2023 pm 05:25 PM

解析PHP面向对象编程中的享元模式在面向对象编程中,设计模式是一种常用的软件设计方法,它可以提高代码的可读性、可维护性和可扩展性。享元模式(Flyweightpattern)是设计模式中的一种,它通过共享对象来降低内存的开销。本文将探讨如何在PHP中使用享元模式来提高程序性能。什么是享元模式?享元模式是一种结构型设计模式,它的目的是在不同对象之间共享相同的

go语言是面向对象的吗go语言是面向对象的吗Mar 15, 2021 am 11:51 AM

go语言既不是面向对象,也不是面向过程,因为Golang并没有明显的倾向,而是更倾向于让编程者去考虑该怎么去用它,也许它的特色就是灵活,编程者可以用它实现面向对象,但它本身不支持面向对象的语义。

python是面向对象还是面向过程python是面向对象还是面向过程Jan 05, 2023 pm 04:54 PM

python是面向对象的。Python语言在设计之初,就定位为一门面向对象的编程语言,“Python中一切皆对象”就是对Pytho 这门编程语言的完美诠释。类和对象是Python的重要特征,相比其它面向对象语言,Python很容易就可以创建出一个类和对象;同时,Python也支持面向对象的三大特征:封装、继承和多态。

PHP面向对象编程入门指南PHP面向对象编程入门指南Jun 11, 2023 am 09:45 AM

PHP作为一种广泛使用的编程语言,已成为构建动态网站和网络应用程序的首选语言之一。其中,面向对象编程(OOP)的概念和技术越来越受到开发者的欢迎和推崇。本篇文章将为读者提供PHP面向对象编程的入门指南,介绍OOP的基本概念,语法和应用。什么是面向对象编程(OOP)?面向对象编程(Object-OrientedProgramming,简称OOP),是一种编程

如何使用Go语言实现面向对象的数据库访问如何使用Go语言实现面向对象的数据库访问Jul 25, 2023 pm 01:22 PM

如何使用Go语言实现面向对象的数据库访问引言:随着互联网的发展,大量的数据需要被存储和访问,数据库成为了现代应用开发中的重要组成部分。而作为一门现代化、高效性能的编程语言,Go语言很适合用来处理数据库操作。而本文将重点讨论如何使用Go语言实现面向对象的数据库访问。一、数据库访问的基本概念在开始讨论如何使用Go语言实现面向对象的数据库访问之前,我们先来了解一下

面向对象是啥意思面向对象是啥意思Jul 17, 2023 pm 02:03 PM

面向对象是软件开发方法,一种编程范式。是一种将面向对象的思想应用于软件开发过程并指导开发活动的系统方法。这是一种基于“对象”概念的方法论。对象是由数据和允许的操作组成的包,它与目标实体有直接的对应关系。对象类定义了一组具有类似属性的对象。面向对象是基于对象的概念,以对象为中心,以类和继承为构建机制,认识、理解和描绘客观世界,设计和构建相应的软件系统。

Python中的面向对象编程Python中的面向对象编程Jun 10, 2023 pm 05:19 PM

Python作为一种高级编程语言,在众多编程语言中占有举足轻重的地位。它的语法简单易学,拥有各种强大的编程库,被广泛应用于数据处理、机器学习、网络编程等领域。而其中最重要的一点便是Python完美支持面向对象编程,本文将重点阐述Python中的面向对象编程。一、面向对象编程的基本概念在面向对象的编程语言中,数据和方法被封装在对象的内部。这使得对象能够独立地进

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尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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.