Skip to content

Instantly share code, notes, and snippets.

@jed
Forked from 140bytes/LICENSE.txt
Created November 28, 2011 15:47
Show Gist options
  • Save jed/1400834 to your computer and use it in GitHub Desktop.
Save jed/1400834 to your computer and use it in GitHub Desktop.
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
Copy link

Nice that it even supports cached results. Pretty cool.

@atk
Copy link

atk commented Nov 29, 2011

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

@jed
Copy link
Author

jed 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