Created
November 4, 2010 22:49
-
-
Save robotlolita/663335 to your computer and use it in GitHub Desktop.
Class instantiation through direct calls.
This file contains 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
/* This is a silly simple attempt at having a object that is always | |
* instantiated whenever it is called directly or with the `new` keyword. | |
* | |
* It relies on `constructor`, basically. But since it uses the | |
* context inside the function and simply compares it's constructor with the | |
* current function, you can't be sure it's always going to be an | |
* auto-instantiation when called directly (without the new keyword), since the | |
* object used as context could have the same constructor as the current | |
* function. | |
* | |
* However, it could also be a feature, so you would be able to `re-initialize` | |
* previous instances. Not sure why you'd ever want that though... | |
*/ | |
/** | |
* madeFrom(constructor, object) -> Boolean | |
* - constructor (`Function`): the function that initializes the instances. | |
* - object (`Object`): the context in which the function is executing. | |
* | |
* Returns whether the given object was initialized by the given constructor or | |
* not. | |
**/ | |
function madeFrom(constructor, object) { | |
return object.constructor == constructor; | |
} | |
/** | |
* instantiate(constructor, arguments) -> Object | |
* - constructor (`Function`): constructor to initialize object. | |
* - args (`Array`): array of arguments to pass the constructor function. | |
* | |
* Instantiate a new object and initializes it with the given constructor and | |
* arguments. This is basically how Python's __init__ methods works. | |
**/ | |
function instantiate(constructor, args) { | |
var Dummy = function(){ }; | |
Dummy.prototype = constructor.prototype; | |
Dummy.prototype.constructor = constructor; | |
/* instantiates and makes the new object ready */ | |
var instance = new Dummy(); | |
/* initialize and return it */ | |
constructor.apply(instance, args); | |
return instance; | |
} | |
/** | |
* new Class(name) | |
* | |
* Dummy class to test instantiation. | |
**/ | |
function Class(name) { | |
if (!madeFrom(Class, this)) return instantiate(Class, arguments); | |
this.name = name; | |
} | |
console.log("direct call:", Class("Sorella").name); | |
/* direct call: Sorella */ | |
console.log("instantiation:", new Class("Sorella").name); | |
/* instantiation: Sorella */ | |
var obj = new Class("Sorella"); | |
Class.call(obj, "Jeff"); | |
console.log("re-initialization:", obj.name); | |
/* re-initialization: Jeff */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment