Table of Contents
1.1 What is a constructor?
2.3 constructor
1.3 Which data types or functions have constructor?
1.4 Simulate the implementation of a new
2.1 prototype(explicit prototype)
2.2 proto(隐式原型)
补充,易错点
Home Web Front-end JS Tutorial Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills

Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills

Mar 17, 2021 am 10:12 AM
javascript prototype prototype chain

Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills

  • Preface
  • 1. Constructor
  • 2. Prototype
  • 3. Instance and prototype
  • 4. Prototype of prototype
  • 5. Prototype chain
  • 6. Summary
  • Write at the end

(Free learning recommendation: javascript video tutorial)

Preface

It's time to look back on the past again. Knowledge is like this. Prototypes and prototype chains were rarely used in my previous internship career - almost none (poof! I'm showing off my cards), but it and this point to the problem Likewise, it is a topic that junior and intermediate front-end developers can never avoid during interviews. Does everyone search for knowledge points related to prototypes every time they read the interview?

Look at this knowledge, you can only know its importance during the exam. It’s like a sincere interview question was once placed in front of me... The topic is brought back, and we will accept this today evil creature!

Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills

1. Constructor

1.1 What is a constructor?

The constructor itself is a function, no different from an ordinary function, but generally capitalizes its first letter for the sake of standardization. The difference between a constructor and an ordinary function is that the function that uses new to generate an instance is a constructor, and the function that is called directly is an ordinary function.

function Person() {
	this.name = 'yuguang';};var person = new Person();console.log(person.name) // yuguang
Copy after login

In this example, Person is a constructor.

1.2 constructor?

constructor Returns a reference to the constructor function when creating the instance object. The value of this property is a reference to the function itself, rather than a string containing the function name.

Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills
You can see that the constructor of the instance object points to its constructor, and its relationship with the prototype will be linked together later.

1.3 Which data types or functions have constructor?

In JavaScript, every object with a prototype automatically gets the constructor property. Except: arguments, Enumerator, Error, Global, Math, RegExp, etc. Except for some special objects, all other built-in JavaScript objects have a constructor attribute. For example: Array, Boolean, Date, Function, Number, Object, Stringetc. All major browsers support this attribute. Open the console and we can verify it

// 字符串console.log('str'.constructor) // ƒ String() { [native code] }console.log('str'.constructor === String) // true// 数组console.log([1,2,3].constructor) // ƒ Array() { [native code] }console.log([1,2,3].constructor === Array) // true// 数字var num = 1console.log(num.constructor) // ƒ Number() { [native code] }console.log(num.constructor === Number) // true// Dateconsole.log(new Date().constructor) // ƒ Date() { [native code] }// 注意!!!不要混淆哦console.log(new Date().getTime().constructor) // ƒ Number() { [native code] }// Booleanconsole.log(true.constructor) // ƒ Boolean() { [native code] }console.log(true.constructor === Boolean) // true// 自定义函数function show(){
	console.log('yuguang');};console.log(show.constructor) // ƒ Function() { [native code] }// 自定义构造函数,无返回值function Person(){
	this.name = name;};var p = new Person()console.log(p.constructor) // ƒ Person()// 有返回值function Person(){
	this.name = name;
	return {
		name: 'yuguang'
	}};var p = Person()console.log(p1.constructor) // ƒ Object() { [native code] }
Copy after login
1.4 Simulate the implementation of a new

Since the difference between the constructor and the ordinary function is only in the calling method, we should understand new.

  • When the new operator is called, the function will always return an object;
  • Usually, this in the constructor points to the returned object Object;

The code is as follows:

通常情况下var MyClass = function(){
	this.name = 'yuguang';};var obj = new MyClass();obj.name; // yuguang特殊情况var MyClass = function(){
	this.name = 'yuguang';
	return {
		name: '老王'
	}};var obj = new MyClass();obj.name // 老王
Copy after login

We use the __proto__ (implicit prototype, will be mentioned below) attribute to simulate the process of new calling the constructor :

var objectNew = function(){
    // 从object.prototype上克隆一个空的对象
    var obj = new Object(); 
    // 取得外部传入的构造器,这里是Person
    var Constructor = [].shift.call( arguments );
    // 更新,指向正确的原型
    obj.__proto__ = Constructor.prototype; //知识点,要考、要考、要考 
    // 借用外部传入的构造器给obj设置属性
    var ret = Constructor.apply(obj, arguments);
    // 确保构造器总是返回一个对象
    return typeof ref === 'object' ? ret : obj;}
Copy after login

Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills

2. Prototype

2.1 prototype(explicit prototype)

JavaScript is a The prototype-based language imitates Java's two type mechanisms when designing: Basic type and Object type. It can be seen that prototypes are very important!

Each object has a prototype object, and classes are defined in the form of functions. Prototype represents the prototype of the function and also represents a collection of members of a class. Look at the picture below:
Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills
You can find the prototype of the Person function itself:

  • ##constructor (Person.prototype.constructor => Person )
  • __proto__ (We call it implicit prototype)
At this point we get the first representation of the relationship between the constructor and the instance prototype Picture:

Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills

So how do we represent the relationship between the instance and the constructor prototype, that is, person and Person.prototype? At this time we will talk about the second attributes:

2.2 proto(隐式原型)

这是每一个JavaScript对象(除了 null )都具有的一个属性,叫__proto__,这是一个访问器属性(即 getter 函数和 setter 函数),通过它可以访问到对象的内部[[Prototype]] (一个对象或 null )。

function Person() {}var person = new Person();console.log(person.__proto__ === Person.prototype); // true
Copy after login

于是我们更新下关系图:

Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills

小结: 每个引用类型的隐式原型都指向它的构造函数的显式原型

2.3 constructor

前文提到了constructor,它与原型的关系也可以添加到这张图里,更新下关系图:

Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills
根据上图的关系,下面这段的结果,大家就一目了然了:

function Person() {}var person = new Person();console.log(person.__proto__ == Person.prototype) // trueconsole.log(Person.prototype.constructor == Person) // true// 顺便学习一个ES5的方法,可以获得对象的原型console.log(Object.getPrototypeOf(person) === Person.prototype) // true
Copy after login

接下来我们要继续思考实例和原型的关系:

三、实例与原型

当读取实例的属性时,如果找不到,就会查找与对象关联的原型中的属性,如果还查不到,就去找原型的原型,一直找到最顶层为止。这样一个查找过程

举个例子:

function Person() {}Person.prototype.name = '老王';var person = new Person();person.name = '余光';console.log(person.name) // 余光delete person.name;console.log(person.name) // 老王
Copy after login

在这个例子中,我们给实例对象 person 添加了 name 属性,当我们打印 person.name 的时候,结果自然为 余光(is me)。

描述:

但是当我们删除了 person 的 name 属性后,再次读取 person.name,从 person 对象中找不到 name 属性就会从 person 的原型也就是 person.proto ,也就是 Person.prototype中查找,幸运的是我们找到了 name 属性,结果为 老王(这…)

总结:

  • 尝试遍历实例a中的所有属性,但没有找到目标属性;
  • 查找name属性的这个请求被委托给该实例a的构造器(A)的原型,它被a.__proto__ 记录着并且指向A.prototype;
  • A.prototype存在目标属性,返回他的值;

但是万一还没有找到呢?原型的原型又是什么呢?

四、原型的原型

在前面,我们已经讲了原型也是一个对象,既然是对象,我们就可以用最原始的方式创建它,那就是:

var obj = new Object();obj.name = '余光'console.log(obj.name) // 余光
Copy after login

其实原型对象就是通过Object构造函数生成的,结合之前所讲,实例的 __proto__ 指向构造函数的 prototype ,可以理解成,Object.prototype()是所有对象的根对象,所以我们再次更新下关系图:

Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills

五、原型链

每个对象拥有一个原型对象,通过 __proto__ 指针指向上一个原型 ,并从中继承方法和属性,同时原型对象也可能拥有原型,这样一层一层,最终指向 null这种关系被称为原型链 (prototype chain),通过原型链一个对象会拥有定义在其他对象中的属性和方法。

这个链条存在着终点,是因为:Object.prototype 的原型是——null,引用阮一峰老师的 《undefined与null的区别》 就是:

null 表示“没有对象”,即该处不应该有值。这句话也意味着 Object.prototype 没有原型
Copy after login

我们最后更新一次关系图,蓝色线条就可以表示原型链这种关系。

Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills

补充,易错点

1.constructor
首先是 constructor 属性,我们看个例子:

function Person() {}var person = new Person();console.log(person.constructor === Person); // true
Copy after login

当获取 person.constructor 时,其实 person 中并没有 constructor 属性,当不能读取到constructor 属性时,会从 person 的原型也就是 Person.prototype 中读取,正好原型中有该属性,所以:

person.constructor === Person.prototype.constructor
Copy after login

2.__proto__

其次是 proto ,绝大部分浏览器都支持这个非标准的方法访问原型,然而它并不存在于 Person.prototype 中,实际上,它是来自于 Object.prototype ,与其说是一个属性,不如说是一个 getter/setter,当使用 obj.proto 时,可以理解成返回了 Object.getPrototypeOf(obj)。

3.真的是继承吗?

最后是关于继承,前面我们讲到“每一个对象都会从原型‘继承’属性”,实际上,继承是一个十分具有迷惑性的说法,引用《你不知道的JavaScript》中的话,就是:

Inheritance means copying. However, JavaScript does not copy the properties of an object by default. Instead, JavaScript just creates an association between two objects, so that one object can access the properties and functions of another object through delegation. , so instead of calling it inheritance, Delegation is more accurate.

6. Summary

  • The function used to generate an instance using new is the constructor, and the direct call is an ordinary function;
  • Every object has a prototype object;
  • The implicit prototype of each reference type points to the explicit prototype of its constructor;
  • Object.prototype is the prototype of all objects Root object;
  • The prototype chain has an end point and will not be searched indefinitely;

Related free learning recommendations:javascript(Video)

The above is the detailed content of Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

Introduction to the new map of Genshin Impact version 4.4 Introduction to the new map of Genshin Impact version 4.4 Jan 31, 2024 pm 06:36 PM

Introducing the new map of Genshin Impact version 4.4. Friends, Genshin Impact 4.4 version also ushered in the Sea Lantern Festival in Liyue. At the same time, a new map area will be launched in version 4.4 called Shen Yu Valley. According to the information provided, Shen Yugu is actually part of Qiaoying Village, but players are more accustomed to calling it Shen Yugu. Now let me introduce the new map to you. Introduction to the new map of Genshin Impact version 4.4. Version 4.4 will open "Chenyu Valley·Shanggu", "Chenyu Valley·Nanling" and "Laixin Mountain" in the north of Liyue. Teleportation anchor points have been opened for travelers in "Chenyu Valley·Shanggu" . ※After completing the prologue of the Demon God Quest·Act 3: The Dragon and the Song of Freedom, the teleportation anchor point will be automatically unlocked. 2. Qiaoyingzhuang When the warm spring breeze once again caressed the mountains and fields of Chenyu, the fragrant

See all articles