JavaScript API design principles
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)

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

PHP API interface: How to use Insomnia Insomnia is a powerful API testing and debugging tool. It can help developers quickly and easily test and verify API interfaces. It supports multiple programming languages and protocols, including PHP. This article will introduce how to use Insomnia to test PHPAPI interface. Step 1: Install InsomniaInsomnia is a cross-platform application that supports Windows, MacOS, and Linux.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
