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:
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:
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 :
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:
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:
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:
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!
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...)
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?
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.

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

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.

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 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.

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

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.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
