Created
October 12, 2011 20:31
-
-
Save tamzinblake/1282443 to your computer and use it in GitHub Desktop.
javascript function prototype
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function foo (p, v) { | |
if (arguments.length > 1) { | |
arguments.callee[p] = v | |
} | |
return arguments.callee[p] | |
} | |
function arrayFunction (arr) { | |
for (var i = 0; i < arr.length; i++) { | |
this[i] = arr[i] | |
} | |
} | |
arrayFunction.prototype = foo | |
var a = new arrayFunction([1, 3, 4]) | |
, b = new arrayFunction([1, 3, 4]) | |
a(1) | |
b(0, -1) |
Simpler example here https://gist.github.com/1282497
The issue is that new
always returns an object, unless the ctor explicitly returns something else. Try this:
function bar (p) { return p }
function barcons () {
var f = function () {}
f.__proto__ = barcons.prototype
return f
}
barcons.prototype=bar
var c = new barcons
c(1)
Of course, this is evil and stupid, and will probably send the interpreter into some kind of crazy bad place. But you're already using arguments.callee, so clearly you're ok with evil ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that
a(1)
throws aTypeError
of typecalled_non_callable
, whilea.__proto__(1)
is fine. That does not make sense.