-
-
Save rwaldron/970812 to your computer and use it in GitHub Desktop.
Object.prototype.toString redefinition for DOM objects with WeakMap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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