Home Web Front-end JS Tutorial Code sniffing in javascript extends native objects and prototypes_javascript tips

Code sniffing in javascript extends native objects and prototypes_javascript tips

May 16, 2016 pm 05:43 PM
prototype

Note: If there is any inappropriateness in the translation, please correct me. I wish you all a happy Double Holidays!
It is not good to extend native objects and prototypes without special needs

Copy code The code is as follows:

//Don’t do this
Array.prototype.map = function() {
// Some code
};

Unless it's worthwhile to do so, e.g. add some ECMAScript5 methods to some older browsers.
In this case, we generally do this:
Copy the code The code is as follows:

if (!Array.prototype.map) {
Array.prototype.map = function() {
//Some code
};
}

If we are more paranoid, in order to prevent others from defining map as other unexpected values, such as true or others, we can change the detection code to the following:
Copy code The code is as follows:

if (typeof Array.prototype.map !== "function") {
Array.prototype.map = function() {
// Some code
};
}

(Although this will break other developers’ map definitions and affect the implementation of their functions)
However, in In a hostile and competitive environment (in other words, when you provide or use a js library), you should not trust anyone. What should you do if someone else's js code is loaded before yours and somehow defines a map() method that is not fully compatible with ES5, causing your code to not run properly?

However, you can trust the browser. If the Webkit kernel implements the map() method, you can rest assured that this method will definitely run normally. Otherwise, you have to use your code to detect it.

Fortunately, this is easy to implement in JavaScript. When you call the toString method of a native function, a string of a function will be returned. The function body of the function is [native code].
For example, under the Chrome console:
Copy the code The code is as follows:

> ; Array.prototype.map.toString();
"function map() { [native code] }"

A proper code inspection is always a slightly unpleasant thing, Because different browsers treat spaces and line breaks too lightly. The test is as follows:
Copy code The code is as follows:

Array.prototype.map.toString() .replace(/s/g, '*');
// "*function*map()*{*****[native*code]*}*" // IE
// " function*map()*{*****[native*code]*}" // FF
// "function*map()*{*[native*code]*}" // Chrome

Simply removing the s will result in a more practical string:
Copy code The code is as follows:

Array.prototype.map.toString().replace(/s/g, '');
// "functionmap(){[nativecode]}"

You can encapsulate it into a reusable shim() function, so that you don’t have to repeat all the operations like!

Array.prototype... Such operations. This function will accept an object as a parameter (for example, Array.prototype), a property to be added (for example, 'map'), and a function to be added.
Copy code The code is as follows:

function shim(o, prop, fn) {
var nbody = "function" prop "(){[nativecode]}";
if (o.hasOwnProperty(prop) &&
o[prop].toString().replace(/s/g, ' ') === nbody) {
//The table name is native!
return true;
}
//Newly added
o[prop] = fn;
}

Test:
Copy code The code is as follows:

//This is the native method
shim(
Array.prototype, 'map',
function(){/*...*/}
); / / true
//This is the newly added method
shim(
Array.prototype, 'mapzer',
function(){alert(this)}
);
[ 1,2,3].mapzer(); // alerts 1,2,3

(End)^_^
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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
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

What are prototypes and prototype chains What are prototypes and prototype chains Nov 09, 2023 pm 05:59 PM

Prototype, an object in js, is used to define the properties and methods of other objects. Each constructor has a prototype attribute. This attribute is a pointer pointing to a prototype object. When a new object is created, the new object will be The prototype attribute of its constructor inherits properties and methods. Prototype chain, when trying to access the properties of an object, js will first check whether the object has this property. If not, then js will turn to the prototype of the object. If the prototype object does not have this property, it will continue to look for the prototype of the prototype.

What is the difference between prototype and prototype chain What is the difference between prototype and prototype chain Nov 09, 2023 pm 04:48 PM

The difference between prototype and prototype chain is: 1. Prototype is an attribute that each object has, including some shared attributes and methods, which is used to realize the sharing and inheritance of attributes and methods between objects, while prototype chain is a The inheritance mechanism is implemented through the prototype relationship between objects, which defines the inheritance relationship between objects so that objects can share the properties and methods of the prototype object; 2. The function of the prototype is to define the shared properties and methods of the object, so that multiple Objects can share the properties and methods of the same prototype object, and the function of the prototype chain is to realize the inheritance relationship between objects, etc.

Performance comparison of Go language and Python: Which one is more suitable for high-performance programming? Performance comparison of Go language and Python: Which one is more suitable for high-performance programming? Jan 30, 2024 am 08:13 AM

Go language and Python are two very popular programming languages, both with their own advantages and characteristics. There are also some differences between the two when it comes to high-performance programming. This article will compare the Go language and Python to explore which one is more suitable for high-performance programming. First, let us understand the Go language. The Go language is an open source programming language developed by Google that focuses on simplicity, efficiency, and concurrency. One of the design goals of the Go language is to provide a high-performance programming experience. It has lightweight coroutines (goro

This domestic free programming tool is popular! Developed by a PhD team from Tsinghua University, it has short response delay and high accuracy. This domestic free programming tool is popular! Developed by a PhD team from Tsinghua University, it has short response delay and high accuracy. Jan 31, 2024 pm 05:03 PM

In the past year, with the widespread application of large model technology, we have witnessed how AI has profoundly changed the way we work. In the field of programming, the intervention of AI will also bring unprecedented convenience to programmers. Recently, Feishen Technology launched FittenCode, an AI code assistant based on a large self-developed code model. It can help programmers complete coding tasks more quickly, accurately, and with higher quality, greatly improve coding efficiency, and contribute to Free and open to users! The product’s official website address: https://code.fittentech.com/FittenCode has quickly become popular since its last release. The development team worked around the clock to bring features,

Choose the right programming language: Compare Go and Python to determine the best choice for your project needs Choose the right programming language: Compare Go and Python to determine the best choice for your project needs Jan 30, 2024 am 08:00 AM

In today's era of rapid technological advancement, the choice of programming language has become very critical. With the continuous development of the software development field, Go language and Python have become two programming languages ​​that have attracted much attention. This article will conduct a comparative analysis of Go language and Python to help readers choose the appropriate programming language according to project needs. First, let us understand the Go language. Go language is a statically compiled programming language developed by Google. It has powerful concurrent processing capabilities and efficient garbage collection mechanism, which is very

In-depth discussion: Analysis of the role of prototypes and prototype chains in object-oriented programming In-depth discussion: Analysis of the role of prototypes and prototype chains in object-oriented programming Jan 11, 2024 am 11:59 AM

In-depth analysis: The role of prototype and prototype chain in object-oriented programming requires specific code examples. In object-oriented programming (OOP), prototype (Prototype) and prototype chain (PrototypeChain) are important concepts. They provide an object-based code reuse mechanism and play a key role in languages ​​such as Javascript. In this article, we'll take a deep dive into the concepts of prototypes and prototype chains, explore their role in OOP, and illustrate with concrete code examples

Explore the peculiarities of prototypes and prototype chains Explore the peculiarities of prototypes and prototype chains Jan 13, 2024 pm 03:50 PM

Exploring the unique features of prototype and prototype chain In JavaScript, prototype and prototype chain are very important concepts. Understanding the unique features of prototypes and prototype chains can help us better understand inheritance and object creation in JavaScript. A prototype is a property owned by every object in JavaScript that points to another object and is used to share properties and methods. Every JavaScript object has a prototype

See all articles