Fixing the JavaScript typeof operator
1 2 3 | <a href= "https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/" target= "_blank" rel= "noopener nofollow" >https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript- typeof -operator/</a><br>javascript 类型判断函数<br> var toType = function (obj) { return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase() }<br><br><br> |
A Better Way?
[[Class]]
Every JavaScript object has an internal property known as [[Class]]
(The ES5 spec uses the double square bracket notation to represent internal properties, i.e. abstract properties used to specify the behavior of JavaScript engines). According to ES5, [[Class]] is “a String value indicating a specification defined classification of objects”. To you and me, that means each built-in object type has a unique non-editable, standards-enforced value for its [[Class]] property. This could be really useful if only we could get at the [[Class]] property…
Object.prototype.toString
…and it turns out we can. Take a look at the ES 5 specification for Object.prototype.toString…
- Let O be the result of calling ToObject passing the this value as the argument.
- Let class be the value of the [[Class]] internal property of O.
- Return the String value that is the result of concatenating the three Strings
"[object "
, class, and"]"
.
In short, the default toString
function of Object returns a string with the following format…
[object [[Class]]]
…where [[Class]] is the class property of the object.
Unfortunately, the specialized built-in objects mostly overwrite Object.prototype.toString
with toString
methods of their own…
1 2 3 4 5 | [1,2,3].toString(); //"1, 2, 3" ( new Date).toString(); //"Sat Aug 06 2011 16:29:13 GMT-0700 (PDT)" /a-z/.toString(); //"/a-z/" |
…fortunately we can use the call
function to force the generic toString
function upon them…
1 2 3 4 5 | Object.prototype.toString.call([1,2,3]); //"[object Array]" Object.prototype.toString.call( new Date); //"[object Date]" Object.prototype.toString.call(/a-z/); //"[object RegExp]" |
Introducing the toType
function
We can take this technique, add a drop of regEx, and create a tiny function – a new and improved version of the typeOf
operator…
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2017-12-29 TMUX会话的使用