您的位置:首页 > Web前端 > JavaScript

编写具有可维护性的JavaScript代码

2016-07-08 15:43 405 查看
首先可定是缩进的问题了,有的人喜欢使用空格键,有的人喜欢使用tab键,不管是使用空格键还是使用tab键,在项目开始前,只要统一规范就可以了。

其次,确保只要通过变量或者函数的名字就能知道这段代码是干什么用的,而不是要读整段代码才知道它是干什么的。例如:

//命名不一致,很难能够理解代码在做什么
const $element = $('.element');

function _privateMethod () {
const self = $(this);
const _internalElement = $('.internal-element');
let $data = element.data('foo');
//... more logic.
}

//命名一致、规范的,可以很容易理解
const $element = $('.element');

function _privateMethod () {
const $this = $(this);
const $internalElement = $('.internal-element');
let elementData = $element.data('foo');
//... more logic.
}


最后是代码模块快的问题。先来看个例子:

//这个例子使用了FetchAPI,假定返回一个json文件并携带了一些内容,创建一个新元素,读取json内容的字符长度,并把它放到一个新标签中
fetch('https://api.somewebsite.io/post/61454e0126ebb8a2e85d', { method: 'GET' })
.then(response => {
if (response.status === 200) {
return response.json();
}
})
.then(json => {
if (json) {
Object.keys(json).forEach(key => {
const item = json[key];
const count = item.content.trim().replace(/\s+/gi, '').length;
const el = `
<div class="foo-${item.className}">
<p>Total characters: ${count}</p>
</div>
`;
const wrapper = document.querySelector('.info-element');

wrapper.innerHTML = el;
});
}
})
.catch(error => console.error(error));


这段代码没有进行模块化,藕合性强每段代码都和其它代码关联在一起,如果有更大更复杂的函数,你可能要debug这个,因为有些地方容易出错,可能是API没有响应,json里的数据发生了变化等等。维护性很差。

让我们看看模块化的代码:

// 这个模块是用来获取响应文本的字符长度
function countCharacters (text) {
const removeWhitespace = /\s+/gi;
return text.trim().replace(removeWhitespace, '').length;
}

// 用DOM创建了一个标签,而不是使用上个例子的字符串,然后把字符长度放到文本节点中
function createWrapperElement (cssClass, content) {
const className = cssClass || 'default';
const wrapperElement = document.createElement('div');
const textElement = document.createElement('p');
const textNode = document.createTextNode(`Total characters: ${content}`);

wrapperElement.classList.add(className);
textElement.appendChild(textNode);
wrapperElement.appendChild(textElement);

return wrapperElement;
}

// foreach内的匿名函数
function appendCharacterCount (config) {
const wordCount = countCharacters(config.content);
const wrapperElement = createWrapperElement(config.className, wordCount);
const infoElement = document.querySelector('.info-element');

infoElement.appendChild(wrapperElement);
}

//最后调用fetch
fetch('https://api.somewebsite.io/post/61454e0126ebb8a2e85d', { method: 'GET' })
.then(response => {
if (response.status === 200) {
return response.json();
}
})
.then(json => {
if (json) {
Object.keys(json).forEach(key => appendCharacterCount(json[key]))
}
})
.catch(error => console.error(error));


这样代码之间就是弱耦合,可维护,结构也清晰。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript 函数