外觀模式
我們?yōu)樯兑褂猛庥^模式呢,其實我們在使用各種 js 庫的時候常常會看到很多的外觀者模式,也正是這些庫的大量使用,所以使得兼容性更廣泛,通過外觀者模式來封裝多個功能,簡化底層操作方法
const A = {
g: function (id) {
return document.querySelector(`#${id}`)
},
css: function (id, key, value) {
this.g(id).style[key] = value
return this
},
attr: function (id, key, value) {
this.g(id)[key] = value
return this
},
html: function (id, html) {
this.g(id).innerHTML = html
return this
}
}
A.css('box','background','red') // 為 id 為 box 的 盒子設(shè)置 background 樣式屬性為 red
數(shù)據(jù)適配
在我們寫方法時,通常會傳遞參數(shù)的形式來傳遞數(shù)據(jù)
function fun(arg1,arg2,arg3,...){
// todo:
}
但是我們更應(yīng)該這樣來寫
function fun(opts = {}) {
const {a,b,c} = opts
// opts.xx
// todo:
}
使用一個對象來接受一些多個參數(shù),使用時進行結(jié)構(gòu)等方式讀取數(shù)據(jù),這樣就避免了多個參數(shù)導(dǎo)致數(shù)據(jù)傳遞錯誤問題了,其實在很多的框架中也常??吹竭@種,比如 Vue 中?
import { createApp, ref } from 'vue'
createApp({
setup() {
return {
count: ref(0)
}
}
}).mount('#app')
這 createApp 方法就單單只是傳遞一個對象來作為一個參數(shù),而不是一二三個參數(shù)
比如 jQuery 中文章來源:http://www.zghlxwxcb.cn/news/detail-829895.html
$.ajax({
url: 'xx',
method: 'get',
dataType: 'json',
success: function (data) {
// todo:
}
})
這種例子也是非常的多,這樣的好處就是方便后期擴展,對于后期堆加參數(shù)更有利。文章來源地址http://www.zghlxwxcb.cn/news/detail-829895.html
到了這里,關(guān)于JavaScript 設(shè)計模式之外觀模式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!