如何确定对象是使用对象字面量还是对象构造函数调用创建的?
更具体地说,您如何确定某个对象是否是使用文字创建的?
var s1 = new String();
var s2 = ""; // Literal
var o1 = new Object();
var o2 = {}; // Literal
var f1 = new Function();
var f2 = function(){}; // Literal
显然,如果您比较上面的任何两个,例如:
var o1 = new Object();
var o2 = {};
alert(o1 == o2);
alert(o1 === o2);
alert(typeof o1);
alert(typeof o2);
... 前两个警报将显示 false
而最后两个警报将显示 [Object object]
例如,如果我想这样做:
function isLiteral(obj, type) {
// ...
}
...人们会如何做呢?
我已经查看了如何确定一个对象是否是 Javascript 中的对象文字?,但它没有回答我的问题。
More specifically, how would you determine if a certain object was created using a literal or not?
var s1 = new String();
var s2 = ""; // Literal
var o1 = new Object();
var o2 = {}; // Literal
var f1 = new Function();
var f2 = function(){}; // Literal
Obviously if you compare any two above, for example:
var o1 = new Object();
var o2 = {};
alert(o1 == o2);
alert(o1 === o2);
alert(typeof o1);
alert(typeof o2);
... The first two alerts will show false
while the last two alerts will give [Object object]
Say for example, if I wanted to do this:
function isLiteral(obj, type) {
// ...
}
... how would one go about doing this?
I have taken a look at How to determine if an object is an object literal in Javascript?, but it does not answer my question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,这两行之间的区别:
...和这两行之间的区别:
...是两个不同的概念。
第一个是原始值和对象之间的区别,而第二个是......同一事物的不同语法。
字符串、数字和布尔值是原始值,而不是对象,但可以使用
new String()
、new Number 包装为对象()
或new Boolean()
。因此,对于这些,typeof
将返回不同的值:但是,对于 Object 和 Function,以下之间的区别:
... 仅在语法上。
o1
和o2
都具有相同的原型
和相同的构造函数
,使得它们在运行时无法区分。Firstly, the difference between these two lines:
...and the difference between these two lines:
...are two different concepts.
The first is the difference between a primitive value and an object, while the second is... different syntax for the same thing.
Strings, numbers and booleans are primitive values, not objects, but can be wrapped as objects using
new String()
,new Number()
ornew Boolean()
. So for these,typeof
will return different values:However, for Object and Function, the difference between:
... is in syntax only.
Both
o1
ando2
have the sameprototype
, and the sameconstructor
, making them indistinguishable at runtime.