Skip to content

Instantly share code, notes, and snippets.

@getify
Created April 3, 2013 00:55
Show Gist options
  • Save getify/5297595 to your computer and use it in GitHub Desktop.
Save getify/5297595 to your computer and use it in GitHub Desktop.
"polymorphism" w/ JS? sorta. kinda. maybe. comes from: https://gist.github.com/getify/5253319
// a sort-of-polyfill for `currentThis` as proposed in: https://gist.github.com/getify/5253319
function lookupFn(oThis,fn) {
var ptr = oThis, i, keys;
while (ptr) {
keys = Object.keys(ptr);
for (i=0; i<keys.length; i++) {
if (ptr[keys[i]] === fn) {
return ptr;
}
}
ptr = Object.getPrototypeOf(ptr);
}
return oThis;
}
var Foo = Object.create(Object.prototype);
Foo.me = "Foo";
Foo.identify = function() {
var currentThis = lookupFn(this,arguments.callee);
// whenever Foo#identify() is called, `currentThis` will
// always be `Foo`, but `this` will continue to follow the
// established rules for determining a `this` binding.
console.log("Me: " + this.me + "; Current: " + currentThis.me);
};
var Bar = Object.create(Foo);
Bar.me = "Bar";
Bar.identify = function() {
var currentThis = lookupFn(this,arguments.callee);
/*super*/currentThis.__proto__.identify.call(this);
console.log("Current: " + currentThis.me);
}
var bar1 = Object.create(Bar);
bar1.me = "bar1";
var bar2 = Object.create(Bar);
bar2.me = "bar2";
Foo.identify(); // "Me: Foo; Current: Foo"
Bar.identify(); // "Me: Bar; Current: Foo" "Current: Bar"
bar1.identify(); // "Me: bar1; Current: Foo" "Current: Bar"
bar2.identify(); // "Me: bar2; Current: Foo" "Current: Bar"
@ljharb
Copy link

ljharb commented Mar 25, 2015

Possibly more efficient:

function findName(oThis, fn) {
  var key;
  for (key in oThis) {
    if (oThis[key] === fn) {
      return key;
    }
  }
}
function lookupFn(oThis, fn) {
  var fnName = findName(oThis, fn);
  var ptr = oThis;
  while (!Object.prototype.hasOwnProperty.call(ptr, fnName)) {
    ptr = Object.getPrototypeOf(ptr);
  }
  return ptr;
}

@ljharb
Copy link

ljharb commented Jun 26, 2015

I just released https://www.npmjs.com/package/find-value-locations which, given an object and a value, returns an array of tuples of [object, ownPropertyName] for everything that matches the value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment