Home Web Front-end JS Tutorial js more elegant compatibility_javascript skills

js more elegant compatibility_javascript skills

May 16, 2016 pm 06:21 PM
compatible

There are various problems in making the underlying interface compatible, which is nothing more than using if to determine which interface the client supports. The most famous example is the event:

Copy code The code is as follows:

var addEvent = function( e, what, how) {
if (e.addEventListener) e.addEventListener(what, how, false)
else if (e.attachEvent) e.attachEvent('on' what, how)
}

Two situations that may be encountered when binding events to elements are considered here - the standard W3C DOM interface and the interface provided by DHTML. Of course, this example is still crude, but it is enough to illustrate the problem.

The original method is to call on-site judgment in the compatibility layer and enter the corresponding if branch. Obviously, this "on-the-spot judgment" method is not efficient. Later, people adopted this method:
Copy code The code is as follows:

if (MSIE) {
addEvent = function(e, what, how) {
e.attachEvent('on' what, how);
}
} else {
addEvent = function(e, what , how) {
e.addEventListener(what, how);
}
}

Bind different codes to addEvent after one judgment, thus eliminating the need to run time branch judgment.

Unfortunately, this problem is not trivial. First of all, it is a very outdated idea to bind "use attachEvent" and "client is MSIE" together. What if Microsoft's conscience finds out one day? This is happening now - IE9 clearly supports the DOM interface, and even DOM3 supports it. As a result, this "conscience discovery" move will break many front-end libraries and they will have to be forced to modify their code (just like when IE8 came). Moreover, this approach does not take into account "unknown clients" - as far as I know, after Google released Chrome, it also caused many class libraries to rewrite their code.

How to do feature detection? Feature detection can minimize the trouble caused by "new clients" - detect the features of the client through a set of codes defined when the class library is initialized, and use this set of detection values ​​to bind the class library code :
Copy code The code is as follows:

var supportsAddEventListener = !!(checkerElement.addEventListener);
if (supportsAddEventListener) {
addEvent = function(e, what, how) {
e.addEventListener(what, how);
}
} else if (supportsAttachEvent) {
addEvent = function(e, what, how) {
e.attachEvent('on' what, how);
}
}

Feature detection is actually Decouple "use a certain client" and "support a certain feature" - let the if branch directly judge "whether the feature is present" (whether the interface is consistent), thereby eliminating the "good intentions" caused by the "conscience discovery" of the client manufacturer Do bad things." In fact, this is also in line with the historical trend - when standard interfaces gradually become popular and clients gradually become "consistent in representation", why not create a consistent compatibility layer interface?

Drop Let’s take a look at the code again. Usually, a piece of code that uses feature detection for compatibility often looks like this:
Copy code The code is as follows:

if (new_interface_detected) {
comp = function() {uses_new_interface};
} else if (old_interface_detected) {
comp = function() {uses_old_interface};
} else {
throw new Error('Unadaptable!')
}

In other words, the process is:

If the client supports the new interface, bind the compatibility layer to the new interface
Otherwise, if the client supports the old interface/inconsistent interface, bind the compatibility layer to the new interface Bind to the old interface
Otherwise, if possible, give error feedback
That is, the compatibility layer program "falls" from high altitude. If the client supports "advanced" features (new interfaces, standard interfaces ), just "catch" it - the compatibility layer will have a home; otherwise, continue to fall - oh, if the old interface catches it, use the old interface; if no one catches it, then - bang - He fell to the ground and shouted with his last breath: "The client you are using is too niche, I can't do anything to you!"

What is this similar to? In fact, if you understand the mechanism of the JavaScript object system, you can make an analogy: isn't this just a prototype? The prototype system takes advantage of this drop - look for a certain member, and if it is defined in this object, return it; otherwise, search upward along the prototype chain (yes, this time it is upward), and so on, until When the prototype chain really reaches the end, undefined is returned.

Just do it! Here we also use addEvent as an example. First, we define an empty driver, which contains nothing:

var nullDriver = {} Then, we create an object and point the prototype chain to it. In the ECMA V5 era, we can use Object.create. Unfortunately, there are still many old clients (otherwise they are compatible), so we craft our own function:
Copy code The code is as follows:

var derive = Object.create ? Object.create: function() {
var T = function() {} ;
return function(obj) {
T.prototype = obj;
return new T
}
}()

You may think of this usage It's weird, but it works without any problems and is not slow - about half as fast as Object.create. We will use this derive to start:
Copy code The code is as follows:

var dhtmlDriver = derive( nullDriver);
var dhtmlDriverBugfix = derive(dhtmlDriver); The bugfix here is a special Driver defined for some "bugs" and special situations. You can ignore it here. Okay, what is addEvent in DHTML?

if (supportsAttachEvent) {
dhtmlDriver.addEvent = function(e, what, how) {
e.attachEvent('on' what, how)
}
}

Then what? The one at the front of the prototype chain should be the W3C standard driver, write it down!
Copy code The code is as follows:

var w3cDriver = derive(dhtmlDriverBugfix);
var w3cDriverBugfix = derive(w3cDriver);

if (supportsAddEventListener) {
w3cDriver.addEvent = function(e, what, how) {
e.addEventListener(what, how)
}
}

Finally, we will put something on it to make the final call interface. (Because w3cDriverBugfix is ​​too ugly...)
Copy code The code is as follows:

var driver = derive (w3cDriverBugfix);

Then it is called. Look, this makes those scary-looking branch judgments simple and effective, without losing the true nature of fallback: calling addEvent on a client that supports addEventListener is equivalent to calling w3cDriver.addEvent, and it will fall to the bottom on a client that does not support addEventListener. Next, for example, call dhtmlDriver.addEvent. In addition, it is easy to perform bugfixes - you can hook in a dedicated "bugfix" layer, while the original layer is not affected at all.

Wait, will it be slow to inherit so many layers? Admittedly, such a deep prototype chain will definitely be slow, but I have a way. Remember what happens when you write to an object's properties?
Copy code The code is as follows:

var ego = function(x) {return x}
for (var each in driver) {
if (! (each in nullDriver)) {
driver[each] = ego(driver[each])
}
}

Yes, the method that was originally high on the prototype chain will suddenly fall to the bottom! This time there is no need to search up the prototype chain, just get the properties directly from the bottom. The reason for using the ego function here is to prevent some browsers from "optimizing" the code here.

Summary Although we talk about compatibility here, the essence of it lies in the language features - using prototypal inheritance, we can complete this troublesome operation very elegantly. Yes, the beauty of a frame should not only be on the outside, but also on the inside - even the most annoying ones - should be equally elegant.

The technology here can be found in dess.
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)

The most stable version of Win10 The most stable version of Win10 Dec 25, 2023 pm 07:58 PM

Many users will encounter freezes or blue screens when operating the computer. At this time, we need to find the most stable win10 version to operate. Overall, it is very easy to use and can make your daily use smoother. The most stable win10 version in history 1. Win10 genuine original system. Here users can use simple operations. The system has been optimized and has strong stability, security and compatibility. Users can follow the steps to achieve the perfect machine. 2. Russian master streamlined The version of win10 has been strictly streamlined and many unnecessary functions and services have been deleted. After streamlining, the system has lower CPU and memory usage and runs faster. 3. Win10 Lite Edition 1909 is installed on multiple computers with different hardware models.

Is Switch2 compatible with Switch cartridges? Is Switch2 compatible with Switch cartridges? Jan 28, 2024 am 09:06 AM

Switch2 is a new model announced by Nintendo at Gamescom 2023. Some players are worried about whether there will be compatibility issues between the new model and the cartridges of previous versions. Let’s take a look. Is switch2 compatible with switch cassette? Answer: switch2 is not compatible with switch cassette. Introduction of Switch 2 cartridges According to information from Nintendo’s production chain company, Switch 2 may use 64GB cartridges. Because it has better performance and supports more 3A game masterpieces, it requires a larger cartridge capacity. Because many game works need to be castrated and compressed before they can be stuffed into a game cartridge. Moreover, Switch cartridges are prone to copying game content, so replace them with new cartridges.

Does Win11 support dynamic wallpapers? Does Win11 support dynamic wallpapers? Jan 01, 2024 pm 06:41 PM

As we all know, a major feature of win11 is its own Android subsystem, which allows us to install Android software without using an emulator. However, there is also the problem of win11 Android application lag. How should this be solved? Is win11 not compatible with dynamic wallpapers? Answer: Win11 is compatible with dynamic wallpapers. If it cannot be used, it may be because the software or system version is lagging behind. If it was just updated, it may be covered by the system wallpaper. 1. If the system or software version is lagging behind, just update the system and dynamic wallpaper software. 2. If it is covered by the system wallpaper, you can try to open "Settings" 3. Then enter the "Background" settings under "Personalization". 4. Then change the personalized background to "Picture" 5. After the modification is completed, you can set the dynamic wallpaper normally

Is Linux system compatible with Android software? Is Linux system compatible with Android software? Mar 20, 2024 pm 02:27 PM

In recent years, the popularity of the Android system in the field of mobile devices has grown rapidly, and many people have begun to pay attention to whether Android applications can also be run on other platforms. As a common operating system, Linux is favored by many people. So the question is, is the Linux system compatible with Android software? The first thing to make clear is that the Linux system and the Android system have certain similarities in the kernel. They are both operating systems based on the Linux kernel. Therefore, theoretically speaking, the Linux system can run

Methods to solve the incompatibility of d3dx9_43.dll Methods to solve the incompatibility of d3dx9_43.dll Feb 24, 2024 pm 10:06 PM

How to resolve d3dx9_43.dll incompatibility. In recent years, the rapid development of computers and games has allowed us to enjoy more entertainment and convenience. However, sometimes when installing or running certain programs, we may encounter some error messages, such as "d3dx9_43.dll is incompatible". In this case, how should we solve this problem? First, let’s understand what this error message means. d3dx9_43.dll is a system file of DirectX, which is used in the operating system

Introduction to the setting method of win10 compatible with win7 Introduction to the setting method of win10 compatible with win7 Jan 03, 2024 pm 05:09 PM

The reason why many friends are still choosing win7 system instead of win10 system is that they are afraid of poor compatibility. In fact, win10 system can now set the compatibility mode of win7. You only need to change the settings in the properties. Let’s take a look at it together. How to make win10 compatible with win71? First, right-click on the program we need to run under win7 system, then open "Properties" 2, then click "Compatibility" above to enter the compatibility tab. 3. Check "Run this program in compatibility mode" in compatibility mode. 4. Then select "Windows 7" from the drop-down menu below. 5. After finishing, just click "Apply" or click "OK".

How to deal with Eclipse version incompatibility How to deal with Eclipse version incompatibility Jan 04, 2024 am 10:29 AM

What should I do if I encounter an incompatible version of Eclipse? [Introduction] As a popular development tool, Eclipse not only provides powerful functions and rich plug-ins, but also has cross-platform features. However, when using Eclipse, you may sometimes encounter version incompatibility issues, which may cause the program to fail to run properly or compile errors. This article will describe how to deal with Eclipse version incompatibility and provide some code examples to solve common compatibility issues. [Solution] Update Ecl

Detailed guide to installing and configuring compatible network points in Win11 Detailed guide to installing and configuring compatible network points in Win11 Jan 09, 2024 pm 02:50 PM

There are many website users who need to use the old version of the browser when browsing, and the new version needs to add compatible outlets before they can be used, so today I will bring you a detailed tutorial on adding compatible outlets in win11. Come and learn. How to add compatible outlets in win11 1. First open the IE browser in the system, click the small gear in the upper right corner of the browser to enter "Settings". 2. Then in the settings menu that opens, open "Compatibility View Settings". 3. Enter the URL to be added in the edit box under Add this website, and then click "Add". 4. Finally, you can see the domain name of the added URL below, and you can access it directly by closing the window.

See all articles