如何确定对象是否是Javascript中的对象文字? [英] How to determine if an object is an object literal in Javascript?

查看:99
本文介绍了如何确定对象是否是Javascript中的对象文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Javascript中确定是否使用对象创建了一个对象-literal 表示法或使用构造函数方法?

Is there any way to determine in Javascript if an object was created using object-literal notation or using a constructor method?

在我看来,你只是访问它的父对象,但如果你传入的对象没有' t有一个对它的父母的引用,我认为你不能告诉它,可以吗?

It seems to me that you just access it's parent object, but if the object you are passing in doesn't have a reference to it's parent, I don't think you can tell this, can you?

推荐答案

我刚刚遇到过这个问题和线程在一个甜蜜的hackfest期间涉及一个圣杯任务来评估一个对象是用{}还是新的Object()创建的(我还是没想到它。)

I just came across this question and thread during a sweet hackfest that involved a grail quest for evaluating whether an object was created with {} or new Object() (i still havent figured that out.)

无论如何,我很惊讶地发现这里发布的isObjectLiteral()函数和我为Pollen.JS项目编写的我自己的isObjLiteral()函数之间的相似性。我相信这个解决方案是在我的Pollen.JS提交之前发布的,所以 - 对你说!我的好处是长度...不到一半(包括你的设置例程),但两者都产生相同的结果。

Anyway, I was suprised to find the similarity between the isObjectLiteral() function posted here and my own isObjLiteral() function that I wrote for the Pollen.JS project. I believe this solution was posted prior to my Pollen.JS commit, so - hats off to you! The upside to mine is the length... less then half (when included your set up routine), but both produce the same results.

看看:


function isObjLiteral(_obj) {
  var _test  = _obj;
  return (  typeof _obj !== 'object' || _obj === null ?
              false :  
              (
                (function () {
                  while (!false) {
                    if (  Object.getPrototypeOf( _test = Object.getPrototypeOf(_test)  ) === null) {
                      break;
                    }      
                  }
                  return Object.getPrototypeOf(_obj) === _test;
                })()
              )
          );
}

此外,还有一些测试内容:

Additionally, some test stuff:


var _cases= {
    _objLit : {}, 
    _objNew : new Object(),
    _function : new Function(),
    _array : new Array(), 
    _string : new String(),
    _image : new Image(),
    _bool: true
};

console.dir(_cases);

for ( var _test in _cases ) {
  console.group(_test);
  console.dir( {
    type:    typeof _cases[_test], 
    string:  _cases[_test].toString(), 
    result:  isObjLiteral(_cases[_test])  
  });    
  console.groupEnd();
}

或者在jsbin.com上...

Or on jsbin.com...

http://jsbin.com/iwuwa

Be当你到达那里时一定要打开萤火虫 - 调试文件是为IE爱好者。

Be sure to open firebug when you get there - debugging to the document is for IE lovers.

这篇关于如何确定对象是否是Javascript中的对象文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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