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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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