下面的代码是一个javascript typeOf函数。我们在这里讨论的不是编码约定,也不是像我这样扩展本机对象是否合法。我想知道在什么情况下,这将不能正确地识别一个对象,并希望能够纠正它。对于99%的个案来说,这是否足够呢?
此外,如果你想办法使这个小,同时保持信息完整,我也很高兴听到这一点。
"use strict"
var FN = Function,
g = FN('return this')(); //jslint safe 'global' reference
Object.typeOf = (function (g) {
return function (o) {
var n = null,
r = false,
nodeType = {
1:'element_node',
2:'attribute_node',
3:'text_node',
4:'cdata_section_node',
5:'entity_reference_node',
6:'entity_node',
7:'processing_instrction_node',
8:'comment_node',
9:'document_node',
10:'document_type_node',
11:'document_fragment_node1',
12:'notation_node'
},
u;
/*********
* Following if statements are direct comparisons
* because any additional checks on o if it equals
* either of these results in an error. So we check
* these first prior to proceeding.
*********/
if (o === u) {
return 'undefined';
}
if (o === n) {
return 'null';
}
/*********
* If we made it this far, just return the set the
* r variable and return at the end;
*********/
switch (o) {
case g:
r = 'global';
break;
case g.document:
r = 'htmldocument';
break;
default:
break;
}
/*********
* Originally a large switch statement changed
* due to below comments.
*********/
if (o.nodeType && nodeType[o.nodeType]) {
r = nodeType[o.nodeType];
}
/*********
* If r is still false, we do a standard check
* using the Object.toString.call method to determine
* its "correct" type;
*********/
return r || ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
}(g));
发布于 2011-09-29 04:52:40
在评估某事之前,必须首先确定评估标准是什么。因此,您必须首先定义“正确标识对象”的含义。
ECMAScript类型操作符返回ECMA-262中指定的值,不幸的是它们与规范中定义的实际类型值不同。该值与内部类属性也没有很大的关系。
此外,主机对象可以返回它们喜欢的任何类型和内部类,如果尝试访问它们,它们甚至可以抛出错误。
在一般意义上,很少有必要知道什么是“类型”,更常见的是想知道某个值是否符合预期目的的特定标准。例如,将DOM元素的样式对象传递给Firefox中的函数返回“cssstyle声明”,在IE中则返回" object“。
这是否符合你“正确识别”的标准(不管它们是什么)?调用者如何看待不同的值?它为什么想知道?
我不知道答案(甚至是可能提出的全部问题),所以我无法确定您的函数是否正确。
对守则的一些评论:
> var FN = Function,
> g = FN('return this')(); //jslint safe 'global' reference
不是:
var g = this;
够了吗?
> Object.typeOf = (function (g) {
> return function (o) {
生命的意义是什么?其中没有运行任何代码,它所做的就是向外部函数的空(或多或少)变量对象添加一个闭包。
> }
> }(g));
如果唯一目的是传递对全局对象的引用,那么:
}
}(this));
会做好这份工作。由于您没有处于严格模式,所以可以在普通函数表达式中使用以下内容:
var global = (function(){return this;})();
大开关语句可以替换为以下内容:
if (typeof o.nodeType == 'number') {
var nodeTypes = {1:'element_node',2:'attribute_node',3:'text_node',4:'cdata_section_node',
5:'entity_reference_node',6:'entity_node',7:'processing_instrction_node',
8:'comment_node',9:'document_node',10:'document_type_node',
11:'document_fragment_node1',12:'notation_node'};
r = nodeTypes[o.nodeType];
}
https://codereview.stackexchange.com/questions/5051
复制相似问题