首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

(转)理清apply(),call()的差异和关系

2012-08-26 
(转)理清apply(),call()的区别和关系?from:http://www.popo4j.com/article/the-differences-of-apply-and-

(转)理清apply(),call()的区别和关系

?

from:http://www.popo4j.com/article/the-differences-of-apply-and-call.html

?

如果没接触过动态语言,以编译型语言的思维方式去理解javaScript将会有种神奇而怪异的感觉,因为意识上往往不可能的事偏偏就发生了,甚至觉得不可理喻.如果在学JavaScript这自由而变幻无穷的语言过程中遇到这种感觉,那么就从现在形始,请放下的您的”偏见”,因为这对您来说绝对是一片新大陆,让JavaScrip慢慢融化以前一套凝固的编程意识,注入新的生机!

好,言归正传,先理解JavaScrtipt动态变换运行时上下文特性,这种特性主要就体现在apply, call两个方法的运用上.

区分apply,call就一句话,

01var?oP = Object.prototype,02toString = oP.toString;0304console.log(toString.call([123]));//[object Array]05console.log(toString.call('123'));//[object String]06console.log(toString.call({a:?'123'}));//[object Object]07console.log(toString.call(/123/));//[object RegExp]08console.log(toString.call(123));//[object Number]09console.log(toString.call(undefined));//[object Undefined]10console.log(toString.call(null));//[object Null]11//....

?

标准浏览器中完美的作到,但是(为什么要说但是呢)IE6中,却会出现以下问题:通过Object.prototype.toString.call获取的 字符串,undefined,null均为Object
所以,我们又要悲剧的先对以上类型进行判断,完整代码:01var?oP = Object.prototype,02toString = oP.toString;0304function?typeOf(value) {05????if?(null?=== value) {06????????return?'null';07????}0809????var?type =?typeof?value;10????if?('undefined'?=== type ||?'string'?=== type) {11????????return?type;12????}1314????var?typeString = toString.call(value);15????switch?(typeString) {16????case?'[object Array]':17????????return?'array';18????case?'[object Date]':19????????return?'date';20????case?'[object Boolean]':21????????return?'boolean';22????case?'[object Number]':23????????return?'number';24????case?'[object Function]':25????????return?'function';26????case?'[object RegExp]':27????????return?'regexp';28????case?'[object Object]':29????????if?(undefined !== value.nodeType) {30????????????if?(3 == value.nodeType) {31????????????????return?(/\S/).test(value.nodeValue) ??'textnode':?'whitespace';32????????????}?else?{33????????????????return?'element';34????????????}35????????}?else?{36????????????return?'object';37????????}38????default:39????????return?'unknow';40????}41}

?

热点排行