I want to write an efficient JavaScript library but have no idea how to start;
I tried reading other people’s class libraries, but I seemed to understand them;
I plan to study the advanced functions of js, but the content in the authoritative book is too scattered,
Even though I remember the "usage", I don't think about the "method" when it comes to "using" it.
Maybe you are like me, there seems to be an invisible force constraining our plans, making us repeatedly think of the limitations of knowledge, causing us to stand still and find it difficult to move forward.
During this period, the pressure doubled due to various assignments, course design, and experimental reports. It's rare to squeeze out a little time, never sleep in, organize and summarize the books I read in the past, just to be closer to writing my own class library.
This article refers to "Javascript Language Essence" and "Effective JavaScript". The examples have been debugged, and after understanding them, I want to make some "profound" principles a little simpler.
1. Variable scope
Scope is like oxygen to programmers. It's everywhere, and you often don't even think about it. But when it is polluted (e.g. using global objects), you can feel suffocated (e.g. application becomes less responsive). JavaScript's core scoping rules are simple, well-designed, and powerful. Using JavaScript effectively requires mastering some basic concepts of variable scope and understanding some edge cases that can lead to elusive and nasty problems.
1.1 Use global variables as little as possible
Javascript makes it easy to create variables in the global namespace. Creating a global variable is effortless because it does not require any form of declaration and is automatically accessed by all code throughout the program.
For beginners like us, when we encounter certain needs (for example, the transmitted data is recorded, used when waiting for a certain function to be called at a certain time; or a certain function is frequently used), we do not hesitate to think of global functions, or even The C language I learned in my freshman year is too deeply rooted in process-oriented thinking, and the system is neatly full of functions. Defining global variables pollutes the shared public namespace and can lead to unexpected naming conflicts. Global variables are also detrimental to modularity because they lead to unnecessary coupling between independent components in a program. Seriously speaking, too many globals (including style sheets, directly defining the style of div or a) will become a catastrophic error when integrated into a multi-person development process. That's why all of jQuery's code is wrapped in an anonymous expression that executes immediately - a self-calling anonymous function. When the browser loads the jQuery file, the self-calling anonymous function immediately starts executing and initializes each module of jQuery to avoid damaging and contaminating global variables and affecting other codes.
In addition, you may think that it is more convenient to "write how you want first and organize it later", but good programmers will constantly pay attention to the structure of the program, continue to classify related functions and separate irrelevant components. and include these behaviors as part of the programming process.
Since the global namespace is the only way for independent components in a JavaScript program to interact, the use of globally named controls is inevitable. Components or libraries have to define some global variables. for use by other parts of the program. Otherwise it's better to use local variables.
The global namespace of JavaScript is also exposed to a global object accessible in the global scope of the program, which serves as the initial value of the this keyword. In web browsers, global objects are bound to the global window variable. This means that you have two ways to create a global variable: declare it using var in the global scope, or add it to the global object. The advantage of using var declaration is that it can clearly express the impact of global variables in the program scope.
Given that references to bound global variables can cause runtime errors, keeping scopes clear and concise will make it easier for users of your code to understand which global variables the program declares.
Since the global object provides a dynamic response mechanism for the global environment, you can use it to query a running environment and detect which features are available on this platform.
eg.ES5 introduces a global JSON object to read and write data in JSON format.
The original design of the data structure course simulated the basic operations of strings, requiring that methods provided by the language itself could not be used. JavaScript implements the basic operations on arrays very well. If it is just for general learning needs, the idea of simulating the methods provided by the language itself is good, but if you really invest in development, there is no need to consider using JavaScript's built-in methods in the first place.
1.2 Avoid using with
The with statement provides any "convenience" that makes your application unreliable and inefficient. We need to call a series of methods on a single object in sequence. Using the with statement can easily avoid repeated references to objects:
Instead of with language, the simple way is to bind the object to a short variable name.
In other cases, the best approach is to explicitly bind the local variable to the relevant property.
1.3 Proficient in closures
There is a single concept for understanding closures:
a) JavaScript allows you to reference variables defined outside the current function.
b) Even if the external function has returned, the current function can still reference the variables defined in the external function
The make function is a closure, and its code refers to two external variables: magicIngredient and filling. Whenever the make function is called, its code can reference these two variables because the closure stores these two variables.
A function can reference any variable within its scope, including parameters and external function variables. We can take advantage of this to write a more general sandwichMaker function.
Closures are one of JavaScript’s most elegant and expressive features and are at the heart of many idioms.
c) Closures can update the value of external variables. In fact, closures store references to external variables, not copies of their values. Therefore, updates can be made for any closure that has access to these external variables.
This example produces an object containing three closures. These three closures are set, type and get properties. They all share access to the val variable. The set closure updates the value of val. Then call get and type to view the updated results.
1.4 Understanding variable declaration improvements
Javascript supports this method of scoping (the reference to the variable foo will be bound to the scope closest to the declaration of the foo variable), but does not support block-level scoping (the scope of the variable definition is not the closest enclosing scope) statement or block of code).
Not understanding this feature will lead to some subtle bugs:
1.5 Beware of awkward scoping of named function expressions
This program looks like it will generate null, but it will actually generate a new object.
Because the scope of the named function variable inherits Object.prototype.constructor (that is, the constructor of Object), just like the with statement, this scope will be affected by the dynamic change of Object.prototype. The way to avoid objects polluting the scope of function expressions in your system is to avoid adding properties to Object.prototype at any time, and to avoid using any local variables with the same name as standard Object.prototype properties.
Another shortcoming in popular JavaScript engines is the promotion of declarations of named function expressions.
Some JavaScript environments even treat the two functions f and g as different objects, resulting in unnecessary memory allocation.
1.6 Beware of awkward scope declarations for local block functions
Javascript does not have block-level scope, so the scope of internal function f should be the entire test function. This is true for some JavaScript environments, but not all JavaScript environments. JavaScript implementations report such functions as errors in strict mode (a program in strict mode with a local block function declaration will report it as a syntax error). There are Helps detect non-portable code and give more sensible and reliable semantics to local block function declarations for future versions of the standard. For this situation, you can consider declaring a local variable in the test function pointing to the global function f.