Skip to content

Instantly share code, notes, and snippets.

@CrabDude
Forked from 140bytes/LICENSE.txt
Created May 27, 2011 16:46
Show Gist options
  • Save CrabDude/995656 to your computer and use it in GitHub Desktop.
Save CrabDude/995656 to your computer and use it in GitHub Desktop.
Force function as constructor

140byt.es::forcetor

A 116 byte tweet-sized snippet of code you can paste into ANY constructor function without modification to force use as a constructor.

How to use

Use the constructor with or without new, and receive back an instance object.

OR...

Copy and paste the following code into the top of your constructor (116 chars):

var a=arguments,b=a[0],c=a.callee;if(!(this instanceof c))return new c(a);if(c==b.callee)return c.apply(this,b);

// This function is intended to be used ONLY as a constructor.
function(
x, // Some variables to pass to the constructor
y // and set on the instance object
){
// BEGIN PASTABLE FORCETOR CODE
var a=arguments, // minification
b=a[0], // first argument, can't use x
// would break no modification paste
c=a.callee, // the constructor
d=this; // only used for the 140 bytes example
if(!(d instanceof c)) // check if "new" was used
return new c(a); // force "new" w/arguments as first argument
if(c==b.callee) // if first argument is an arguments object
// that originated from this constructor
return c.apply(d,b); // call constructor w/new instance and proper arguments
// END PASTABLE FORCETOR CODE
// YOUR CONSTRUCTOR CODE HERE
d.x=x; // set values on this with confidence
d.y=y; // knowing with certainty you're in a constructor
}
var A = function(x,y){var a=arguments,b=a[0],c=a.callee,d=this;if(!(d instanceof c))return new c(a);if(c==b.callee)return c.apply(d,b);d.x=x;d.y=y;};
var a = A(1,2);
console.log(a.x, a.y); // 1 2
console.log(a instanceof A); // true
var b = new A(3,4);
console.log(b.x,b.y); // 3 4
console.log(b instanceof A); // true
function(x,y){var a=arguments,b=a[0],c=a.callee,d=this;if(!(d instanceof c))return new c(a);if(c==b.callee)return c.apply(d,b);d.x=x;d.y=y;}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
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": "forcetor",
"description": "Force function use only as a constructor",
"keywords": [
"140bytes",
"constructor",
"ctor",
"forcetor"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment