更多關於代碼設計以及如何更好地編寫代碼的問題。代碼本身就像它應該的那樣工作。JavaScript代碼設計
一些關於代碼本身:功能檢查作爲第一個參數傳遞的對象,要麼返回字符串對象與(array
,date
,xmlhttprequest
等)的類型或布爾與比較對象時字符串值。
該函數還可以迭代對象數組並返回布爾值,布爾結果數組或對象。
(function (global) {
"use strict";
Object.type = function type(testObject, testAgainst, returnType) {
var result, getType = function (object) {
var result;
if (object && object.nodeType !== undefined) {
result = 'dom';
}
else if (object === global) {
result = 'global';
}
else {
result = ({}).toString.call(object).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
return result;
};
if (getType(testAgainst) !== 'undefined') {
if (getType(testAgainst) === 'string') {
return getType(testObject) === testAgainst;
}
else if (getType(testAgainst) === 'array') {
if (getType(returnType) === 'undefined') {
returnType = 'boolean';
}
result = {
'boolean': function() {
return testObject.every(function (member, index) {
return getType(member) === testAgainst[index];
});
},
'array': function() {
return testObject.map(function (member, index) {
return getType(member) === testAgainst[index];
});
},
'object': function() {
var result = {};
testObject.forEach(function (member, index) {
result[ getType(member) ] = getType(member) === testAgainst[index];
});
return result;
}
};
return result[ returnType ]();
}
}
return getType(testObject);
};
}(this));
使用示例:
(function() {
var objects = [null, 0, undefined, new Date(), new XMLHttpRequest(), function() {}, {}, [], 'string'],
matches = ['null', 'number', 'undefined', 'date', 'xmlhttprequest', 'function', 'object', 'array', 'string'],
misses = ['array', 'number', 'string', 'date', 'xmlhttprequest', 'function', 'object', 'number', 'string'];
console.dir({
"objects array: ": objects,
"matches array: ": matches,
"misses array: ": misses,
"Object.type({})": Object.type({}), //returns 'object'
"Object.type(2013, 'number')": Object.type(2013, 'number'), //returns true
"Object.type(objects, matches)": Object.type(objects, matches), //returns true
"Object.type(objects, misses)": Object.type(objects, misses), //returns false
"Object.type(objects, matches, 'object')": Object.type(objects, matches, 'object'),
"Object.type(objects, matches, 'array')": Object.type(objects, matches, 'array'), //returns Array[9] (true, true, true, true, true, true, true, true, true)
"Object.type(objects, misses, 'object')": Object.type(objects, misses, 'object'),
"Object.type(objects, misses, 'array')": Object.type(objects, misses, 'array') //returns Array[9] (false, true, false, true, true, true, true, false, true)
});
}());
與設計,主要是我的錯誤是,大部分代碼是內部嵌套if
語句的問題。
我可以對此代碼做哪些設計更改以使其可以投入生產?
編輯:
我創建了一個gist,我更新的基於評論(https://gist.github.com/silverstrike/5108601)
如果條件有什麼問題? – Oliver 2013-03-07 13:24:15
@Oliver:if條件沒有錯。但在我看來,如果大部分代碼都在嵌套條件下,那麼設計可以得到改進。 – silverstrike 2013-03-07 13:32:17
它看起來很好 – Sebas 2013-03-07 13:33:03