亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

深入淺析JavaScript的API設(shè)計(jì)原則

 更新時(shí)間:2016年06月14日 10:44:14   作者:賣(mài)燒烤夫斯基  
這篇文章主要介紹了JavaScript的API設(shè)計(jì)原則,包括接口的流暢性,一致性,參數(shù)的處理,可擴(kuò)展性,對(duì)錯(cuò)誤的處理,可預(yù)見(jiàn)性,注釋和文檔的可讀性,本文介紹的非常詳細(xì),具有參考借鑒價(jià)值,感興趣的朋友一起學(xué)習(xí)吧

一、接口的流暢性

好的接口是流暢易懂的,他主要體現(xiàn)如下幾個(gè)方面:

1.簡(jiǎn)單

操作某個(gè)元素的css屬性,下面是原生的方法:

document.querySelectorAll('#id').style.color = 'red'; 

封裝之后

function a(selector, color) {
document.querySelectorAll(selector)[].style.color = color
}
a('#a', 'red'); 

從幾十個(gè)字母長(zhǎng)長(zhǎng)的一行到簡(jiǎn)簡(jiǎn)單單的一個(gè)函數(shù)調(diào)用,體現(xiàn)了api簡(jiǎn)單易用

2.可閱讀性

a('#a', 'red')是個(gè)好函數(shù),幫助我們簡(jiǎn)單實(shí)用地改變某個(gè)元素,但問(wèn)題來(lái)了,如果第一次使用改函數(shù)的人來(lái)說(shuō)會(huì)比較困惑,a函數(shù)是啥函數(shù),沒(méi)有人告訴他。開(kāi)發(fā)接口有必要知道一點(diǎn),人都是懶惰的,從顏色賦值這個(gè)函數(shù)來(lái)說(shuō),雖然少寫(xiě)了代碼,但是增加了記憶成本。每次做這件事情的時(shí)候都需要有映射關(guān)系。 a---->color. 如果是簡(jiǎn)單的幾個(gè)無(wú)所謂,但是通常一套框架都有幾十甚至上百的api,映射成本增加會(huì)使得程序員哥哥崩潰。 我們需要的就是使得接口有意義,下面我們改寫(xiě)一下a函數(shù):

function letSomeElementChangeColor(selector, color) {
document.querySelectorAll(selector, color);
} 

letSomeElementChangeColor相對(duì)于a來(lái)說(shuō)被賦予了語(yǔ)言意義,任何人都會(huì)知道它的意義

3.減少記憶成本

我們剛剛的函數(shù)也是這樣的它太長(zhǎng)了letSomeElementChangeColor雖然減少了映射成本,但是增加了記憶成本。要知道,包括學(xué)霸在內(nèi),任何人都不喜歡被單詞。原生獲取dom的api也同樣有這個(gè)問(wèn)題 document.getElementsByClassName; document.getElementsByName; document.querySelectorAll;這些api給人的感覺(jué)就是單詞太長(zhǎng)了,雖然他給出的意義是很清晰,然而這種做法是建立在犧牲簡(jiǎn)易性的基礎(chǔ)上進(jìn)行的。于是我們又再次改寫(xiě)這個(gè)之前函數(shù)

function setColor(selector, color) {
xxxxxxxxxxxx
} 

在意義不做大的變化前提下,縮減函數(shù)名稱(chēng)。使得它易讀易記易用;

4.可延伸

所謂延伸就是指函數(shù)的使用像流水一樣按照書(shū)寫(xiě)的順序執(zhí)行形成執(zhí)行鏈條:

document.getElementById('id').style.color = 'red';
document.getElementById('id').style.fontSize = 'px';
document.getElementById('id').style.backgourdColor = 'pink'; 

用我們之前的之前的方法是再次封裝兩個(gè)函數(shù) setFontSize, setbackgroundColor; 然后執(zhí)行它們 setColor('id', 'red');setFontSiez('id', '12px'); setbackgroundColor('id', 'pink'); 顯然,這樣的做法沒(méi)有懶出境界來(lái);id元素每次都需要重新獲取,影響性能,失??;每次都需要添加新的方法 失敗 每次還要調(diào)用這些方法,還是失敗。下面我們將其改寫(xiě)為可以延伸的函數(shù) 首先將獲取id方法封裝成對(duì)象,然后再對(duì)象的每個(gè)方法中返回這個(gè)對(duì)象:

function getElement(selector) {
this.style = document.querySelecotrAll(selector).style;
}
getElement.prototype.color = function(color) {
this.style.color = color;
return this;
}
getElement.prototype.background = function(bg) {
this.style.backgroundColor = color;
return this;
}
getElement.prototype.fontSize = function(size) {
this.style.fontSize = size;
return this;
}
//調(diào)用
var el = new getElement('#id')
el.color('red').background('pink').fontSize('px'); 

簡(jiǎn)單、流暢、易讀后面我們會(huì)在參數(shù)里面講到如何繼續(xù)優(yōu)化。所以,大家都比較喜歡用jquery的api,雖然一個(gè)$符號(hào)并不代表任何現(xiàn)實(shí)意義,但簡(jiǎn)單的符號(hào)有利于我們的使用。它體現(xiàn)了以上的多種原則,簡(jiǎn)單,易讀,易記,鏈?zhǔn)綄?xiě)法,多參處理。

nightware:

document.getElementById('id').style.color = 'red';
document.getElementById('id').style.fontSize = 'px';
document.getElementById('id').style.backgourdColor = 'pink'; 

dream:

$('id').css({color:'red', fontSize:'12px', backgroundColor:'pink'}) 

二、一致性

1.接口的一致性

相關(guān)的接口保持一致的風(fēng)格,一整套 API 如果傳遞一種熟悉和舒適的感覺(jué),會(huì)大大減輕開(kāi)發(fā)者對(duì)新工具的適應(yīng)性。 命名這點(diǎn)事:既要短,又要自描述,最重要的是保持一致性 “在計(jì)算機(jī)科學(xué)界只有兩件頭疼的事:緩存失效和命名問(wèn)題” — Phil Karlton 選擇一個(gè)你喜歡的措辭,然后持續(xù)使用。選擇一種風(fēng)格,然后保持這種風(fēng)格。

Nightware:

setColor,
letBackGround
changefontSize
makedisplay

dream:

setColor;
setBackground;
setFontSize
set.........

盡量地保持代碼風(fēng)格和命名風(fēng)格,使人讀你的代碼像是閱讀同一個(gè)人寫(xiě)的文章一樣。

三、參數(shù)的處理

1.參數(shù)的類(lèi)型

判斷參數(shù)的類(lèi)型為你的程序提供穩(wěn)定的保障

//我們規(guī)定,color接受字符串類(lèi)型
function setColor(color) {
if(typeof color !== 'string') return;
dosomething
} 

2.使用json方式傳參

使用json的方式傳值很多好處,它可以給參數(shù)命名,可以忽略參數(shù)的具體位置,可以給參數(shù)默認(rèn)值等等 比如下面這種糟糕的情況:

function fn(param1, param2...............paramN)

你必須對(duì)應(yīng)地把每一個(gè)參數(shù)按照順序傳入,否則你的方法就會(huì)偏離你預(yù)期去執(zhí)行,正確的方法是下面的做法。

function fn(json) {
//為必須的參數(shù)設(shè)置默認(rèn)值
var default = extend({
param: 'default',
param: 'default'
......
},json)
} 

這段函數(shù)代碼,即便你不傳任何參數(shù)進(jìn)來(lái),他也會(huì)預(yù)期運(yùn)行。因?yàn)樵诼暶鞯臅r(shí)候,你會(huì)根據(jù)具體的業(yè)務(wù)決定參數(shù)的缺省值。

四、可擴(kuò)展性

軟件設(shè)計(jì)最重要的原則之一:永遠(yuǎn)不修改接口,指擴(kuò)展它!可擴(kuò)展性同時(shí)會(huì)要求接口的職責(zé)單一,多職責(zé)的接口很難擴(kuò)展。 舉個(gè)栗子:

//需要同時(shí)改變某個(gè)元素的字體和背景 
// Nightware:
function set(selector, color) {
document.querySelectroAll(selector).style.color = color;
document.querySelectroAll(selector).style.backgroundColor = color;
}
//無(wú)法擴(kuò)展改函數(shù),如果需要再次改變字體的大小的話,只能修改此函數(shù),在函數(shù)后面填加改變字體大小的代碼
//Dream
function set(selector, color) {
var el = document.querySelectroAll(selector);
el.style.color = color;
el.style.backgroundColor = color;
return el;
}
//需要設(shè)置字體、背景顏色和大小
function setAgain (selector, color, px) {
var el = set(selector, color)
el.style.fontSize = px;
return el;
} 

以上只是簡(jiǎn)單的添加顏色,業(yè)務(wù)復(fù)雜而代碼又不是你寫(xiě)的時(shí)候,你就必須去閱讀之前的代碼再修改它,顯然是不符合開(kāi)放-封閉原則的。修改后的function是返回了元素對(duì)象,使得下次需要改變時(shí)再次得到返回值做處理。

2.this的運(yùn)用

可擴(kuò)展性還包括對(duì)this的以及call和apply方法的靈活運(yùn)用:

function sayBonjour() {
alert(this.a)
}
obj.a = ;
obj.say = sayBonjour;
obj.say();//
//or
sayBonjour.call||apply(obj);// 

五、對(duì)錯(cuò)誤的處理

1.預(yù)見(jiàn)錯(cuò)誤

可以用 類(lèi)型檢測(cè) typeof 或者try...catch。 typeof 會(huì)強(qiáng)制檢測(cè)對(duì)象不拋出錯(cuò)誤,對(duì)于未定義的變量尤其有用。

2.拋出錯(cuò)誤

大多數(shù)開(kāi)發(fā)者不希望出錯(cuò)了還需要自己去找?guī)?duì)應(yīng)得代碼,最好方式是直接在console中輸出,告訴用戶發(fā)生了什么事情。我們可以用到瀏覽器的輸出api:console.log/warn/error。你還可以為自己的程序留些后路: try...catch。

function error (a) {
if(typeof a !== 'string') {
console.error('param a must be type of string')
}
}
function error() {
try {
// some code excucete here maybe throw wrong 
}catch(ex) {
console.wran(ex);
}
} 

六、可預(yù)見(jiàn)性

可預(yù)見(jiàn)性味程序接口提供健壯性,為保證你的代碼順利執(zhí)行,必須為它考慮到非正常預(yù)期的情況。我們看下不可以預(yù)見(jiàn)的代碼和可預(yù)見(jiàn)的代碼的區(qū)別用之前的setColor

//nighware
function set(selector, color) {
document.getElementById(selector).style.color = color;
}
//dream
zepto.init = function(selector, context) {
var dom
// If nothing given, return an empty Zepto collection
if (!selector) return zepto.Z()
// Optimize for string selectors
else if (typeof selector == 'string') {
selector = selector.trim()
// If it's a html fragment, create nodes from it
// Note: In both Chrome and Firefox , DOM error 
// is thrown if the fragment doesn't begin with <
if (selector[] == '<' && fragmentRE.test(selector))
dom = zepto.fragment(selector, RegExp.$, context), selector = null
// If there's a context, create a collection on that context first, and select
// nodes from there
else if (context !== undefined) return $(context).find(selector)
// If it's a CSS selector, use it to select nodes.
else dom = zepto.qsa(document, selector)
}
// If a function is given, call it when the DOM is ready
else if (isFunction(selector)) return $(document).ready(selector)
// If a Zepto collection is given, just return it
else if (zepto.isZ(selector)) return selector
else {
// normalize array if an array of nodes is given
if (isArray(selector)) dom = compact(selector)
// Wrap DOM nodes.
else if (isObject(selector))
dom = [selector], selector = null
// If it's a html fragment, create nodes from it
else if (fragmentRE.test(selector))
dom = zepto.fragment(selector.trim(), RegExp.$, context), selector = null
// If there's a context, create a collection on that context first, and select
// nodes from there
else if (context !== undefined) return $(context).find(selector)
// And last but no least, if it's a CSS selector, use it to select nodes.
else dom = zepto.qsa(document, selector)
}
// create a new Zepto collection from the nodes found
return zepto.Z(dom, selector)
} 

以上是zepto的源碼,可以看見(jiàn),作者在預(yù)見(jiàn)傳入的參數(shù)時(shí)做了很多的處理。其實(shí)可預(yù)見(jiàn)性是為程序提供了若干的入口,無(wú)非是一些邏輯判斷而已。zepto在這里使用了很多的是非判斷,同時(shí)導(dǎo)致了代碼的冗長(zhǎng),不適合閱讀??傊深A(yù)見(jiàn)性真正需要你做的事多寫(xiě)一些對(duì)位置實(shí)物的參數(shù)。把外部的檢測(cè)改為內(nèi)部檢測(cè)。是的使用的人用起來(lái)舒心放心開(kāi)心。吶!做人嘛最重要的就是海森啦。

七、注釋和文檔的可讀性

一個(gè)最好的接口是不需要文檔我們也會(huì)使用它,但是往往接口量一多和業(yè)務(wù)增加,接口使用起來(lái)也會(huì)有些費(fèi)勁。所以接口文檔和注釋是需要認(rèn)真書(shū)寫(xiě)的。注釋遵循簡(jiǎn)單扼要地原則,給多年后的自己也給后來(lái)者看:

//注釋接口,為了演示PPT用
function commentary() {
//如果你定義一個(gè)沒(méi)有字面意義的變量時(shí),最好為它寫(xiě)上注釋?zhuān)篴:沒(méi)用的變量,可以刪除
var a;
//在關(guān)鍵和有歧義的地方寫(xiě)上注釋?zhuān)q如畫(huà)龍點(diǎn)睛:路由到hash界面后將所有的數(shù)據(jù)清空結(jié)束函數(shù)
return go.Navigate('hash', function(){
data.clear();
});
} 

最后

推薦markdown語(yǔ)法書(shū)寫(xiě)API文檔,github御用文檔編寫(xiě)語(yǔ)法。簡(jiǎn)單、快速,代碼高亮、話不多說(shuō)上圖

以上所述是小編給大家介紹的JavaScript的API設(shè)計(jì)原則的全部敘述,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論