Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active April 11, 2018 18:17
Show Gist options
  • Save dfkaye/a0355b3cbf5717dfc7d13bbbd8c66ac0 to your computer and use it in GitHub Desktop.
Save dfkaye/a0355b3cbf5717dfc7d13bbbd8c66ac0 to your computer and use it in GitHub Desktop.
tests that an argument is the scope or that a value is the scope's value
// 10 April 2018
// Tuesday fun with this and that
// Object.prototype.isThis(argument) tests whether an argument is the scope or a value is the scope's value
Object.prototype.isThis = function isThis(o) {
return o == null ? isThis.call(o, this) : o === this.valueOf();
}
console.log(
// true
'a'.isThis('a'),
(0).isThis(0),
(false).isThis(false),
Object.isThis(Object),
window.isThis(window),
window.isThis(),
this.isThis(this),
this.isThis(),
// assignment
(function() {
var a = { 'test': 'test'};
var b = a;
return a.isThis(b)
})(),
// constructors
(function() {
function A(name) { this.name = name || 'defaultName'; }
var name = 'test'
var a = new A(name);
var b = new A(name);
return a.isThis(a) && (a.name).isThis(name) && (b.name).isThis(a.name);
})(),
// context: weakness in the 'context' or 'scope' mechanism
// where scope is null, it is set to outer scope, etc...
{}.isThis.call(undefined, null)
);
// true true true true true true true true true true true
console.log(
// false
('').isThis(' '),
(0).isThis(false),
(1).isThis(true),
(1).isThis('1'),
({}).isThis({}),
([0]).isThis([0]),
// constructors
(function() {
function A() {}
var a = new A();
var b = new A();
return b.isThis(a);
})(),
// context
{}.isThis.call({}, null),
);
// false false false false false false false false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment