Skip to content

Instantly share code, notes, and snippets.

@jed jed/LICENSE.txt forked from 140bytes/LICENSE.txt
Created Nov 28, 2011

Embed
What would you like to do?
turn the `new` keyword into a function
function d(
a, // constructor function
b, // arguments
c // placeholder for length
){
return( // return the result of
d[c=b?-~b.length:1] || ( // the cached function or
d[c] = Function( // a new function that takes
"a,b,c", // a constructor, arguments, and an index
"return new a(" + // and returns a new instance of the constructor
Array(c) // with
.join(",b[c++]") // the inline arguments
.slice(1) + // (sliced to remove leading comma)
")"
)
)
)(a,b,0) // called with the constructor and arguments
}
function d(a,b,c){return(d[c=b?-~b.length:1]||(d[c]=Function("a,b,c","return new a("+Array(c).join(",b[c++]").slice(1)+")")))(a,b,0)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Jed Schmidt <http://jed.is>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "newOperator",
"description": "Turns the `new` operator into a function",
"keywords": [
"new",
"ES3",
"function",
"instance"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>95</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var myFunction = function d(a,b,c){return(d[c=b?-~b.length:1]||(d[c]=Function("a,b,c","return new a("+Array(c).join(",b[c++]").slice(1)+")")))(a,b,0)}
document.getElementById( "ret" ).innerHTML = myFunction(Date, [1995, 11, 24]).getYear()
</script>
@eliperelman

This comment has been minimized.

Copy link

commented Nov 28, 2011

Nice that it even supports cached results. Pretty cool.

@atk

This comment has been minimized.

Copy link

commented Nov 29, 2011

@jed: I like the way you iterated the arguments array without actually iterating it, it is very creative!

@jed

This comment has been minimized.

Copy link
Owner Author

commented Nov 29, 2011

@atk, that's all @WebReflection!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.