欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

typeof func ==='function'的疑惑 jsisFunction工具类 

程序员文章站 2022-07-13 23:17:40
...

 

呵呵 有的人看到这个题目可能觉得,咦,这不就是判断对象是否是function吗?

 

我记得以前吧有一个同学义正言辞地说我研究过YUI,不相信我给你贴代码。 

 

 

var L = Y.Lang || (Y.Lang = {});

var TYPES = {
    'undefined'        : 'undefined',
    'number'           : 'number',
    'boolean'          : 'boolean',
    'string'           : 'string',
    '[object Function]': 'function',
    '[object RegExp]'  : 'regexp',
    '[object Array]'   : 'array',
    '[object Date]'    : 'date',
    '[object Error]'   : 'error'
},
TOSTRING     = Object.prototype.toString;

/**
 * <p>
 * Determines whether or not the provided item is a function.
 * Note: Internet Explorer thinks certain functions are objects:
 * </p>
 *
 * <pre>
 * var obj = document.createElement("object");
 * Y.Lang.isFunction(obj.getAttribute) // reports false in IE
 * &nbsp;
 * var input = document.createElement("input"); // append to body
 * Y.Lang.isFunction(input.focus) // reports false in IE
 * </pre>
 *
 * <p>
 * You will have to implement additional tests if these functions
 * matter to you.
 * </p>
 *
 * @method isFunction
 * @static
 * @param o The object to test.
 * @return {boolean} true if o is a function.
 */
L.isFunction = function(o) {
    return L.type(o) === 'function';
};

L.type = function(o) {
    return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};

 

 

呵呵 结果自己就傻了,请仔细看看,人家不是typeof 是自己封装的api------L.type

 

 

只所以想说一个这样的话题是因为,很多的流行的插件包括一些老一点的脚本库在isFunction的判断上多有这样的写法

 

 

/*
判断参数是否是function
*/
isFunction: function(source){
    return typeof(source) === "function";
}

 

我们先做个测试吧。

 

 

var obj = document.createElement("object");
console.log(typeof(obj.getAttribute) === "function");
console.log((typeof(obj.getAttribute)) ==== "function");

 

请再IE浏览器下测试

 

你会发现false了? 呵呵

 

我们再回过头看看上面YUI的代码,看什么-----------------------注释

 

 

 <p>
 * Determines whether or not the provided item is a function.
 * Note: Internet Explorer thinks certain functions are objects:
 * </p>
 

翻译一下吧:IE会认为某些functions是object (言辞很严谨啊)

 

ps题外话-------最近看到有一个大三学生实习面试的时候说自己有3年工作经验(注意说的是工作经验,还义正言辞),一天打2W行代码。(好吧本人表示膜拜,佩服,建议没毕业的和毕业的多向这个同学学习

 

。。。。。。。。。。。。。。。。。。。

 

 

简单地总结一下:

 

我们无论在设计api还是一般的代码编写的时候,最好注意一下这些细节的问题,有的时候报错了,需要一段一段地去注释去排除,结果发现原来自己的工具类api错误了。

 

只是一些细节和代码严谨度的思考。供参考

 

下面链接是我贴出的自己整理的lang的lib的一个isFunction的写法(和JQuery还有tangram是一致的)

http://zhangyaochun.iteye.com/blog/1205543

 

当然说明一下,这个api在IE下浏览器下判断isFunction的时候也有缺陷的

看看Jquery的源码注释

They return false on IE (#2968).

 

 

 

//测试代码
var obj = document.createElement("object");
Object.prototype.toString.call(obj.getAttribute);