Home Web Front-end JS Tutorial JavaScript Advanced Series—Prototype

JavaScript Advanced Series—Prototype

Feb 07, 2017 pm 05:20 PM

  • Property lookup

  • Prototype properties

  • Performance

  • Prototypes that extend built-in types

  • Summary

JavaScript does not include the traditional class inheritance model, but uses the prototype prototype model.

is often mentioned as a shortcoming of JavaScript. In fact, the prototype-based inheritance model is more powerful than traditional class inheritance. Implementing the traditional class inheritance model is easy, but implementing prototypal inheritance in JavaScript is much more difficult. (It is for example fairly trivial to build a classic model on top of it, while the other way around is a far more difficult task.)

JavaScript is the only widely used language based on prototypal inheritance. So it takes some time to understand the difference between the two inheritance models.

The difference is the way JavaScript uses prototype chain inheritance.

function Foo() {
    this.value = 42;
}
Foo.prototype = {
    method: function() {}
};

function Bar() {}

// 设置Bar的prototype属性为Foo的实例对象
Bar.prototype = new Foo();
Bar.prototype.foo = 'Hello World';

// 修正Bar.prototype.constructor为Bar本身
Bar.prototype.constructor = Bar;

var test = new Bar() // 创建Bar的一个新实例

// 原型链
test [Bar的实例]
    Bar.prototype [Foo的实例] 
        { foo: 'Hello World' }
        Foo.prototype
            {method: ...};
            Object.prototype
                {toString: ... /* etc. */};
Copy after login

In the above example, the test object inherits from Bar.prototype and Foo.prototype; therefore, it can access the prototype method of Foo. At the same time, it can also access the Foo instance property value defined on the prototype. Note that new Bar() does not create a new Foo instance, but reuses the instance on its prototype; therefore, all Bar instances will share the same value property.

Property lookup

When looking for a property on an object, JavaScript traverses up the prototype chain until it finds a property with a given name.

When you reach the top of the prototype chain - that is, Object.prototype - but the specified property is still not found, undefined will be returned.

Note: Do not use Bar.prototype = Foo, as this will not execute Foo's prototype, but will point to function Foo. So the prototype chain will go back to Function.prototype instead of Foo.prototype, so the method will not be on Bar's prototype chain.

Prototype attribute

When the attribute is used to create a prototype chain, any type of value can be assigned to it (prototype). However, assigning the atomic type to the prototype will be ignored.

function Foo() {}
Foo.prototype = 1; // 无效
Copy after login

Assigning the object to prototype, as shown in the above example, will dynamically create the prototype chain.

Performance

If a property is at the upper end of the prototype chain, it will have a negative impact on the search time. In particular, attempting to access a property that does not exist will traverse the entire prototype chain.

And, when using a for in loop to traverse the properties of an object, all properties on the prototype chain will be accessed.

Extending prototypes of built-in types

One wrong feature that is often used is to extend Object.prototype or other prototype objects of built-in types.

This technique is called monkey patching and breaks encapsulation. Although it is widely used in some JavaScript libraries such as Prototype, I still don't think it is a good idea to add some non-standard functions to the built-in types.

The only reason to extend built-in types is to be consistent with new JavaScript, such as Array.forEach.

Summary

Before writing complex JavaScript applications, fully understanding how prototype chain inheritance works is a must for every JavaScript programmer. Beware of performance issues caused by long prototype chains, and know how to improve performance by shortening the prototype chain. Furthermore, never extend prototypes of built-in types except for compatibility with new JavaScript engines.

Note: This is a commonly used method in the programming field, called Backport, which means adding new patches to the old version.

The above is the content of JavaScript Advanced Series - Prototype. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

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

See all articles