Skip to content

Instantly share code, notes, and snippets.

Created May 13, 2011 08:46
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 anonymous/970223 to your computer and use it in GitHub Desktop.
Save anonymous/970223 to your computer and use it in GitHub Desktop.
Object.prototype.toString redefinition for DOM objects with WeakMap
"use strict";
/* ***
** ENVIRONNEMENT SETTING
*/
(function(global){
var constructorName = "MyDOMNode";
var MyDOMNodeMap = WeakMap();
var currentToString = Object.prototype.toString;
global[constructorName] = function(){
var ObjectToReturn = {};
/* Create the object with property properties, prototype, etc. */
MyDOMNodeMap.set(ObjectToReturn, undefined); // value does not matter.
// What is important is the fact that we have a weak map
return ObjectToReturn;
}
Object.prototype.toString = function(){
return MyDOMNodeMap.has(this) ?
"[object "+constructorName+"]": // custom value
currentToString.apply(this, arguments); // default value
}
})(window);
(function(global){
var constructorName = "MyDOMElement";
var MyDOMNodeMap = WeakMap();
var currentToString = Object.prototype.toString;
global[constructorName] = function(){
var ObjectToReturn = {};
/* Create the object with property properties, prototype, etc. */
MyDOMNodeMap.set(ObjectToReturn, undefined); // value does not matter.
// What is important is the fact that we have a weak map
return ObjectToReturn;
}
Object.prototype.toString = function(){
return MyDOMNodeMap.has(this) ?
"[object "+constructorName+"]": // custom value
currentToString.apply(this, arguments); // default value
}
})(window);
/* ***
** USER CODE
*/
var o1 = {};
console.log(Object.prototype.toString.call(o1));
var o2 = [];
console.log(Object.prototype.toString.call(o2));
var p1 = Proxy.create({});
console.log(Object.prototype.toString.call(p1));
var p2 = Proxy.createFunction({}, function(){}, function(){});
console.log(Object.prototype.toString.call(p2));
var o3 = new MyDOMNode(); // usually, the constructor cannot be called directly, but you get my point
console.log(Object.prototype.toString.call(o3));
var o4 = new MyDOMElement(); // usually, the constructor cannot be called directly, but you get my point
console.log(Object.prototype.toString.call(o4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment