Skip to content

Instantly share code, notes, and snippets.

@kangax
Forked from jeresig/isObjectLiteral.html
Created July 23, 2009 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kangax/153295 to your computer and use it in GitHub Desktop.
Save kangax/153295 to your computer and use it in GitHub Desktop.
/*
Checks that `toString` of constructor's prototype has "special" behavior (i.e. is `Object.prototype.toString`) as per 15.2.4.2
Cons:
- Relies on `constructor` property of an object (as well as `toString` of constructor's prototype) being present and not augmented
(will fail on host objects in IE that lack constructor, but could be guarded against)
- Does not differentiate between Object objects created implicitly via function constructor and those created explicitly via Object
Pros:
- Does not rely on func. decomp.
- Should work across windows and in any ES3 compliant implementation
*/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<!-- Online here: http://ejohn.org/files/bugs/isObjectLiteral/ -->
<title>isObjectLiteral</title>
<style>
li { background: green; } li.FAIL { background: red; }
iframe { display: none; }
</style>
</head>
<body>
<ul id="results"></ul>
<script>
function isObjectLiteral(obj) {
var _toString = obj.constructor.prototype.toString;
try {
return _toString.call([]) === '[object Array]';
} catch(e) {
return false;
}
}
// Function serialization is not permitted
// Does not work across all browsers
Function.prototype.toString = function(){};
log("{}", {}, true);
log("new Date", new Date, false);
var fn = function(){};
log("fn", fn, false);
log("new fn", new fn, false);
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){
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment