Identify a window object
by Sir_Pepe
JavaScript
function isWindow(x){
var y = new Function('return this')();
return Object.prototype.toString.call(x) === Object.prototype.toString.call(y);
}
function test(obj, expected, title){
var p = document.createElement('p');
p.innerHTML += title + ': ';
var result = isWindow(obj);
var color = (result === expected) ? 'green' : 'red';
p.innerHTML += '<span style="color: ' + color + ' ">' + result + '</span>';
document.body.appendChild(p);
}
test(window, true, 'window');
test(self, true, 'window eqivalent');
test({}, false, 'generic object');
test({ toString: function(){ return Object.prototype.toString.call(window); } }, false, 'fake window object');