Skip to content

Instantly share code, notes, and snippets.

@junosuarez
Created March 13, 2013 05:20
Show Gist options
  • Save junosuarez/5149561 to your computer and use it in GitHub Desktop.
Save junosuarez/5149561 to your computer and use it in GitHub Desktop.
What's the best way to build a function with prototypically inherited properties which still evaluates to typeof => 'function'?
var proto = {foo: true}
var f1 = Object.create(proto, function () { return 1 })
f1() // => 1
f1.foo // => true
// :)
typeof f1 // => 'object'
// :(
var f2 = function () { return 2 })
f2.__proto__ = proto // :(
f2() // => 2
f2.foo // => true
typeof f2 // => 'function'
// :)
// is there a way without using __proto__?
@jdalton
Copy link

jdalton commented Mar 13, 2013

var f1 = Object.create(proto, function () { return 1 })
f1()   // => 1
f1.foo // => true

That shoudn't do that. See http://es5.github.com/#x15.2.3.5.

@jdalton
Copy link

jdalton commented Mar 13, 2013

Right, __proto__ allows more than just objects, it's in ES6 so \o/

@junosuarez
Copy link
Author

Woah. You're quite right, the first example is not a function.

@junosuarez
Copy link
Author

Hmm. The problem with f2 is that it's now not instanceof Function, which also means it doesn't have the methods in Function.prototype. When I try proto = Object.create(Function.prototype, {}) strange things happen. Unfortunately I don't have time to fully understand what I'm seeing now, and I get the intuition that I'm "doing it wrong".

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