Some time ago, we organized and optimized our native module API (iOS and Android modules are encapsulated into JavaScript interfaces), so I studied several articles on JavaScript API design. Although they are old articles, I benefited a lot. I will record them here.
Good API design: achieve the goal of abstraction while being self-describing.
With a well-designed API, developers can get started quickly. There is no need to hold manuals and documents frequently, and there is no need to frequently visit the technical support community.
Smooth interface
Method chain: smooth and easy to read, easier to understand
//常见的 API 调用方式:改变一些颜色,添加事件监听 var elem = document.getElementById("foobar"); elem.style.background = "red"; elem.style.color = "green"; elem.addEventListener('click', function(event) { alert("hello world!"); }, true); //(设想的)方法链 API DOMHelper.getElementById('foobar') .setStyle("background", "red") .setStyle("color", "green") .addEvent("click", function(event) { alert("hello world"); });
Set and get operations can be combined into one; the more methods, the more difficult the documentation may be Write
var $elem = jQuery("#foobar"); //setter $elem.setCss("background", "green"); //getter $elem.getCss("color") === "red"; //getter, setter 合二为一 $elem.css("background", "green"); $elem.css("color") === "red";
Consistency
Relevant interfaces maintain a consistent style. If a complete set of APIs conveys a familiar and comfortable feeling, it will greatly ease developers' adaptability to new tools.
Name things: short, self-descriptive, and most importantly consistent
“There are only two hard problems in computer science: cache-invalidation and naming things ."
"There are only two headaches in computer science: cache invalidations and naming problems"
— Phil Karlton
Pick a phrasing you like, and stick with it. Choose a style and keep it that way.
Processing parameters
You need to consider how people use the method you provide. Will it be called repeatedly? Why is it called repeatedly? How does your API help developers reduce duplicate calls?
Receive map mapping parameters, callbacks or serialized attribute names, which not only makes your API cleaner, but also makes it more comfortable and efficient to use.
jQuery's css() method can set styles for DOM elements:
jQuery("#some-selector") .css("background", "red") .css("color", "white") .css("font-weight", "bold") .css("padding", 10);
This method can accept a JSON object:
jQuery("#some-selector").css({ "background" : "red", "color" : "white", "font-weight" : "bold", "padding" : 10 }); //通过传一个 map 映射绑定事件 jQuery("#some-selector").on({ "click" : myClickHandler, "keyup" : myKeyupHandler, "change" : myChangeHandler }); //为多个事件绑定同一个处理函数 jQuery("#some-selector").on("click keyup change", myEventHandler);
Processing type
Definition method, you need to decide what parameters it can receive. We don't know how people use our code, but we can be more forward-looking and consider what parameter types we support.
//原来的代码 DateInterval.prototype.days = function(start, end) { return Math.floor((end - start) / 86400000); }; //修改后的代码 DateInterval.prototype.days = function(start, end) { if (!(start instanceof Date)) { start = new Date(start); } if (!(end instanceof Date)) { end = new Date(end); } return Math.floor((end.getTime() - start.getTime()) / 86400000); };
With just 6 lines of code added, our method is powerful enough to receive Date objects, numeric timestamps, even things like Sat Sep 08 2012 15:34:35 GMT+0200 (CEST) String
If you need to ensure the type of the incoming parameter (string, number, boolean), you can convert it like this:
function castaway(some_string, some_integer, some_boolean) { some_string += ""; some_integer += 0; // parseInt(some_integer, 10) 更安全些 some_boolean = !!some_boolean; }
Handle undefined
In order to make your API More robust. If you need to identify whether a real undefined value is passed in, you can check the arguments object:
function testUndefined(expecting, someArgument) { if (someArgument === undefined) { console.log("someArgument 是 undefined"); } if (arguments.length > 1) { console.log("然而它实际是传进来的"); } } testUndefined("foo"); // 结果: someArgument 是 undefined testUndefined("foo", undefined); // 结果: someArgument 是 undefined , 然而它实际是传进来的
Name the parameters
event.initMouseEvent( "click", true, true, window, 123, 101, 202, 101, 202, true, false, false, false, 1, null);
Event.initMouseEvent This method is simply crazy. If you don’t read the documentation, who can Can you tell what each parameter means?
Give each parameter a name and assign a default value. For example,
event.initMouseEvent( type="click", canBubble=true, cancelable=true, view=window, detail=123, screenX=101, screenY=202, clientX=101, clientY=202, ctrlKey=true, altKey=false, shiftKey=false, metaKey=false, button=1, relatedTarget=null);
ES6 or Harmony has default parameter values and rest parameters.
Parameters receive JSON objects
Instead of receiving a bunch of parameters, it is better to receive a JSON object:
function nightmare(accepts, async, beforeSend, cache, complete, /* 等28个参数 */) { if (accepts === "text") { // 准备接收纯文本 } } function dream(options) { options = options || {}; if (options.accepts === "text") { // 准备接收纯文本 } }
It is also simpler to call:
nightmare("text", true, undefined, false, undefined, /* 等28个参数 */); dream({ accepts: "text", async: true, cache: false });
Parameters Default value
It is best to have a default value for the parameters. The preset default value can be overridden through jQuery.extend() http://underscorejs.org/#extend) and Protoype's Object.extend.
var default_options = { accepts: "text", async: true, beforeSend: null, cache: false, complete: null, // … }; function dream(options) { var o = jQuery.extend({}, default_options, options || {}); console.log(o.accepts); } dream({ async: false }); // prints: "text"
Extensibility
Callbacks
Through callbacks, API users can overwrite a certain part of your code. Open some functions that require customization into configurable callback functions, allowing API users to easily override your default code.
Once the API interface receives a callback, make sure to document it and provide code examples.
Events
It is best to know the name of the event interface. You can freely choose the event name to avoid duplication of names with native events.
Handling Errors
Not all errors are useful for developers to debug code:
// jQuery 允许这么写 $(document.body).on('click', {}); // 点击时报错 // TypeError: ((p.event.special[l.origType] || {}).handle || l.handler).apply is not a function // in jQuery.min.js on Line 3
Such errors are painful to debug. Don’t waste developers’ time. Tell them directly. What mistake did they make:
if (Object.prototype.toString.call(callback) !== '[object Function]') { // 看备注 throw new TypeError("callback is not a function!"); }
Note: typeof callback === "function" will cause problems in old browsers, and object will be treated as a function.
Predictability
A good API is predictable and developers can infer its usage based on examples.
Modernizr's feature detection is an example:
a) It uses attribute names that completely match HTML5, CSS concepts and APIs
b) Each individual detection is consistent Returning true or false values
// 所有这些属性都返回 'true' 或 'false' Modernizr.geolocation Modernizr.localstorage Modernizr.webworkers Modernizr.canvas Modernizr.borderradius Modernizr.boxshadow Modernizr.flexbox
relies on concepts that developers are already familiar with and can be predictable.
jQuery’s selector syntax is an obvious example. CSS1-CSS3 selectors can be used directly in its DOM selector engine.
$("#grid") // Selects by ID $("ul.nav > li") // All LIs for the UL with class "nav" $("ul li:nth-child(2)") // Second item in each list
Proportional coordination
A good API is not necessarily a small API. The size of the API must be commensurate with its function.
For example, Moment.js, a well-known date parsing and formatting library, can be called balanced. Its API is both concise and functional.
With a function-specific library like Moment.js, it’s important to keep the API focused and small.
Writing API Documentation
One of the most difficult tasks in software development is writing documentation. In fact, everyone hates writing documentation. The complaint is that there is no easy-to-use documentation tool.
The following are some automatic document generation tools:
YUIDoc (requires Node.js, npm)
JsDoc Toolkit ( requires Node.js, npm)
- ##Markdox (requires Node.js, npm)
- Dox (requires Node.js, npm)
- Docco (requires Node.js, Python, CoffeeScript)
- JSDuck (reqires Ruby, gem)
- JSDoc 3 (requires Java)

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.