myVar.constructor - 或 - typeof myVar ---有什么区别? [英] myVar.constructor --or-- typeof myVar ---What is the difference?

查看:102
本文介绍了myVar.constructor - 或 - typeof myVar ---有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别......

What is the difference between...

if(myVar.constructor == String)

if(typeof myVar == "string")


推荐答案

表达式 myVar.constructor 只返回成员constructor的值。对于给定对象来说,拥有一个指向字符串(或其他任何东西)的构造函数是完全可能和合法的。例如

The expression myVar.constructor just returns the value of the member "constructor". It's completely possible and legal for a given object to have a constructor which points to string (or anything else). For example

function Apple() {}
var x = new Apple();
x.constructor = String
if (x.constructor == String) {
  // True
}

使用 typeof 运算符提供您正在寻找的信息

Using the typeof operator though provides the information you're looking for

if (typeof myVar == 'string') {
  // It's a string
}

这篇关于myVar.constructor - 或 - typeof myVar ---有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆