如何确定对象是否是Javascript中的对象文字?

时间:2009-07-23 18:15:35

标签: javascript oop object-literal

有没有办法在Javascript中确定对象是使用object-literal表示法还是使用构造函数方法创建的?

在我看来,你只是访问它的父对象,但如果你传入的对象没有引用它的父对象,我认为你不能告诉它,你呢?

9 个答案:

答案 0 :(得分:11)

编辑:我正在将“对象文字”解释为使用对象文字 Object构造函数创建的任何内容。这就是John Resig最有可能的意思。

即使.constructor被污染了,或者对象是在另一个框架中创建的,我也有一个功能。请注意,Object.prototype.toString.call(obj) === "[object Object]"(有些人可能认为)无法解决此问题。

function isObjectLiteral(obj) {
    if (typeof obj !== "object" || obj === null)
        return false;

    var hasOwnProp = Object.prototype.hasOwnProperty,
    ObjProto = obj;

    // get obj's Object constructor's prototype
    while (Object.getPrototypeOf(ObjProto = Object.getPrototypeOf(ObjProto)) !== null);

    if (!Object.getPrototypeOf.isNative) // workaround if non-native Object.getPrototypeOf
        for (var prop in obj)
            if (!hasOwnProp.call(obj, prop) && !hasOwnProp.call(ObjProto, prop)) // inherited elsewhere
                return false;

    return Object.getPrototypeOf(obj) === ObjProto;
};


if (!Object.getPrototypeOf) {
    if (typeof ({}).__proto__ === "object") {
        Object.getPrototypeOf = function (obj) {
            return obj.__proto__;
        };
        Object.getPrototypeOf.isNative = true;
    } else {
        Object.getPrototypeOf = function (obj) {
            var constructor = obj.constructor,
            oldConstructor;
            if (Object.prototype.hasOwnProperty.call(obj, "constructor")) {
                oldConstructor = constructor;
                if (!(delete obj.constructor)) // reset constructor
                    return null; // can't delete obj.constructor, return null
                constructor = obj.constructor; // get real constructor
                obj.constructor = oldConstructor; // restore constructor
            }
            return constructor ? constructor.prototype : null; // needed for IE
        };
        Object.getPrototypeOf.isNative = false;
    }
} else Object.getPrototypeOf.isNative = true;

以下是测试用例的HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <!-- Online here: http://code.eligrey.com/testcases/all/isObjectLiteral.html -->
    <title>isObjectLiteral</title>
    <style type="text/css">
    li { background: green; } li.FAIL { background: red; }
    iframe { display: none; }
    </style>
</head>
<body>
<ul id="results"></ul>
<script type="text/javascript">
function isObjectLiteral(obj) {
    if (typeof obj !== "object" || obj === null)
        return false;

    var hasOwnProp = Object.prototype.hasOwnProperty,
    ObjProto = obj;

    // get obj's Object constructor's prototype
    while (Object.getPrototypeOf(ObjProto = Object.getPrototypeOf(ObjProto)) !== null);

    if (!Object.getPrototypeOf.isNative) // workaround if non-native Object.getPrototypeOf
        for (var prop in obj)
            if (!hasOwnProp.call(obj, prop) && !hasOwnProp.call(ObjProto, prop)) // inherited elsewhere
                return false;

    return Object.getPrototypeOf(obj) === ObjProto;
};


if (!Object.getPrototypeOf) {
    if (typeof ({}).__proto__ === "object") {
        Object.getPrototypeOf = function (obj) {
            return obj.__proto__;
        };
        Object.getPrototypeOf.isNative = true;
    } else {
        Object.getPrototypeOf = function (obj) {
            var constructor = obj.constructor,
            oldConstructor;
            if (Object.prototype.hasOwnProperty.call(obj, "constructor")) {
                oldConstructor = constructor;
                if (!(delete obj.constructor)) // reset constructor
                    return null; // can't delete obj.constructor, return null
                constructor = obj.constructor; // get real constructor
                obj.constructor = oldConstructor; // restore constructor
            }
            return constructor ? constructor.prototype : null; // needed for IE
        };
        Object.getPrototypeOf.isNative = false;
    }
} else Object.getPrototypeOf.isNative = true;

// Function serialization is not permitted
// Does not work across all browsers
Function.prototype.toString = function(){};

// The use case that we want to match
log("{}", {}, true);

// Instantiated objects shouldn't be matched
log("new Date", new Date, false);

var fn = function(){};

// Makes the function a little more realistic
// (and harder to detect, incidentally)
fn.prototype = {someMethod: function(){}};

// Functions shouldn't be matched
log("fn", fn, false);

// Again, instantiated objects shouldn't be matched
log("new fn", new fn, false);

var fn2 = function(){};

log("new fn2", new fn2, false);

var fn3 = function(){};

fn3.prototype = {}; // impossible to detect (?) without native Object.getPrototypeOf

log("new fn3 (only passes with native Object.getPrototypeOf)", new fn3, false);

log("null", null, false);

log("undefined", undefined, false);


/* Note:
 * The restriction against instantiated functions is
 * due to the fact that this method will be used for
 * deep-cloning an object. Instantiated objects will
 * just have their reference copied over, whereas
 * plain objects will need to be completely cloned.
 */

var iframe = document.createElement("iframe");
document.body.appendChild(iframe);

var doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc.write("<body onload='window.top.iframeDone(Object);'>");
doc.close();

function iframeDone(otherObject){
    // Objects from other windows should be matched
    log("new otherObject", new otherObject, true);
}

function log(msg, a, b) {
  var pass = isObjectLiteral(a) === b ? "PASS" : "FAIL";

  document.getElementById("results").innerHTML +=
    "<li class='" + pass + "'>" + msg + "</li>";
}


</script>
</body>
</html>

答案 1 :(得分:11)

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

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

看看:

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;
                })()
              )
          );
}

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

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上...

http://jsbin.com/iwuwa

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

答案 2 :(得分:6)

听起来你正在寻找这个:

function Foo() {}

var a = {};
var b = new Foo();

console.log(a.constructor == Object); // true
console.log(b.constructor == Object); // false

对象上的构造函数属性是指向用于构造它的函数的指针。在上面的示例b.constructor == Foo中。如果对象是使用大括号(数组文字表示法)或使用new Object()创建的,则其构造函数属性将为== Object

更新: crescentfresh指出$(document).constructor == Object而不是等于jQuery构造函数,所以我做了一点挖掘。似乎通过使用对象文字作为对象的原型,您渲染构造函数属性几乎一文不值:

function Foo() {}
var obj = new Foo();
obj.constructor == Object; // false

但:

function Foo() {}
Foo.prototype = { objectLiteral: true };
var obj = new Foo();
obj.constructor == Object; // true

在另一个答案here中有一个非常好的解释,以及更为复杂的解释here

我认为其他答案是正确的,并没有真正的方法可以检测到这一点。

答案 3 :(得分:4)

对象文字是用于定义对象的符号 - 在javascript中,它始终采用由大括号括起的名称 - 值对的形式。一旦执行了这个,就无法判断该对象是否是由这种符号创建的(实际上,我认为这可能是过度简化,但基本上是正确的)。你只有一个对象。这是关于js的一个伟大的事情,因为有许多捷径可以做更长的写作时间。简而言之,字面符号代替了必须写:

var myobject = new Object();

答案 4 :(得分:4)

你想要的是:

Object.getPrototypeOf(obj) === Object.prototype

这将检查该对象是使用new Object(){...}创建的普通对象,而不是Object的某些子类。

答案 5 :(得分:2)

没有办法区分从对象文字构建的对象和用其他方法构建的对象。

这有点像询问你是否可以通过赋值'2'或'3-1'来确定是否构造了数值变量;

如果您需要这样做,则必须在对象文字中加入一些特定的签名,以便稍后检测。

答案 6 :(得分:1)

我有同样的问题,所以我决定采用这种方式:

function isPlainObject(val) {
  return val ? val.constructor === {}.constructor : false;
}
// Examples:
isPlainObject({}); // true
isPlainObject([]); // false
isPlainObject(new Human("Erik", 25)); // false
isPlainObject(new Date); // false
isPlainObject(new RegExp); // false
//and so on...

答案 7 :(得分:1)

如今,有一个更优雅的解决方案可以完全回答您的问题:

function isObject(value) {
  return value !== null && value !== undefined && Object.is(value.constructor, Object)
}

// Test stuff below //

class MyClass extends Object {
  constructor(args) {
    super(args)
  }
  say() {
    console.log('hello')
  }
}

function MyProto() {
  Object.call(this)
}
MyProto.prototype = Object.assign(Object.create(Object.prototype), {

  constructor: MyProto,

  say: function() {
    console.log('hello')
  }

});

const testsCases = {
  objectLiteral: {},
  objectFromNew: new Object(),
  null: null,
  undefined: undefined,
  number: 123,
  function: new Function(),
  array: new Array([1, 2, 3]),
  string: new String('foobar'),
  image: new Image(),
  bool: true,
  error: new Error('oups'),
  myClass: new MyClass(),
  myProto: new MyProto()
}

for (const [key, value] of Object.entries(testsCases)) {
  console.log(`${key.padEnd(15)} => ${isObject(value)}`)
}

最诚挚的问候

答案 8 :(得分:0)

这里 11 岁的问题是我的整洁解决方案,对边缘情况建议持开放态度; 步骤 -> 仅查找对象然后比较以检查属性 -> 对象文字没有长度、原型和边缘情况 stringyfy 属性。

尝试测试 JSON 和 Object.create(Object.create({cool: "joes"})).

 "use strict"
let isObjectL = a => { 
        if (typeof a !=='object' || ['Number','String','Boolean', 'Symbol'].includes(a.constructor.name)) return false;
       let props = Object.getOwnPropertyNames(a);
        if ( !props.includes('length') && !props.includes('prototype') || !props.includes('stringify')) return true;
         };


let A={type:"Fiat", model:"500", color:"white"};
let B= new Object();
let C = { "name":"John", "age":30, "city":"New York"};
let D= '{ "name":"John", "age":30, "city":"New York"}';
let E = JSON.parse(D);
let F = new Boolean();
let G = new Number();
    
    console.log(isObjectL(A));
    
    console.log(isObjectL(B));
    
    console.log(isObjectL(C));
    
    console.log(isObjectL(D));
    
    console.log(isObjectL(E));
    
    console.log(isObjectL(JSON));
    
    console.log(isObjectL(F));
    
    console.log(isObjectL(G));
    
    console.log(isObjectL(
Object.create(Object.create({cool: "joes"}))));

    
    console.log(isObjectL());

另一个显示内部工作的变体

isObject=function(a) { 
    let exclude = ['Number','String','Boolean', 'Symbol'];
    let types = typeof a;
    let props = Object.getOwnPropertyNames(a);
    console.log((types ==='object' && !exclude.includes(a.constructor.name) &&
    ( !props.includes('length') && !props.includes('prototype') && !props.includes('stringify'))));
    return `type: ${types} props: ${props}
    ----------------`}
    
    A={type:"Fiat", model:"500", color:"white"};
B= new Object();
C = { "name":"John", "age":30, "city":"New York"};
D= '{ "name":"John", "age":30, "city":"New York"}';
E = JSON.parse(D);
F = new Boolean();
G = new Number();
    
    console.log(isObject(A));
    
    console.log(isObject(B));
    
    console.log(isObject(C));
    
    console.log(isObject(D));
    
    console.log(isObject(E));
    
    console.log(isObject(JSON));
    
    console.log(isObject(F));
    
    console.log(isObject(G));
    
    console.log(isObject(
Object.create(Object.create({cool: "joes"}))));