Skip to content

Instantly share code, notes, and snippets.

/gist:970223
Created May 13, 2011

Embed
What would you like to do?
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
You can’t perform that action at this time.