Last active
August 29, 2015 14:02
-
-
Save jussi-kalliokoski/7f86ff181a01c671d047 to your computer and use it in GitHub Desktop.
Constructors?
This file contains hidden or 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
// 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 |
This file contains hidden or 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
// 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 |
This file contains hidden or 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
// 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 |
This file contains hidden or 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
// 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