Skip to content

Instantly share code, notes, and snippets.

@jussi-kalliokoski
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jussi-kalliokoski/7f86ff181a01c671d047 to your computer and use it in GitHub Desktop.
Save jussi-kalliokoski/7f86ff181a01c671d047 to your computer and use it in GitHub Desktop.
Constructors?
// method as a constructor.
function MyClass () {
this.isInitialized = false;
}
MyClass.prototype.initialize = function () {
this.initialized = true;
};
var myInstance = new MyClass();
var otherInstance = new myInstance.initialize();
console.log(otherInstance.initialized); // true
console.log(otherInstance instanceof myInstance.initialize); // true
// a function that needs to be called with `new`, but isn't a constructor.
function MyClass () {
if ( !( this instanceof MyClass ) ) {
throw new Error("Must be called with new.");
}
return Object.create(null);
}
var myInstance = new MyClass();
console.log(myInstance instanceof MyClass); // false
// a constructor that can't be called with new.
function MyClass () {
if ( this instanceof MyClass ) {
throw new Error("cannot be called with new");
}
return Object.create(MyClass.prototype);
}
var myInstance = MyClass();
console.log(myInstance instanceof MyClass); // true
// a function that returns the constructed object, which however isn't an instance of MyClass.
function MyClass () {
this.__proto__ = {};
}
var myInstance = new MyClass();
console.log(myInstance instanceof MyClass); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment