Last active
January 3, 2017 17:51
-
-
Save ramonvictor/931b52116c3b2d3adb38f9831d4446da to your computer and use it in GitHub Desktop.
Mimic `new` operator implementation, just for learning purposes.
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
/* | |
* `Cat` module sample. | |
*/ | |
function Cat(bar) { | |
this.bar = bar; | |
} | |
Cat.prototype.foo = 'hello'; | |
/* | |
* Logging classical `new Cat()` usage. | |
*/ | |
var cat1 = new Cat('barz'); | |
console.log(cat1); // {bar: "barz"} | |
console.log(cat1.foo); // "hello" | |
console.log(cat1 instanceof Cat); // true | |
/* | |
* Custom implementation to mimic `new` keyword behaviour. | |
* The logic you see below is based on what MDN documentation describes as `new` operator behaviour, check following quote: | |
* | |
* "When the code new Foo(...) is executed, the following things happen: | |
* | |
* 1. A new object is created, inheriting from Foo.prototype. | |
* 2. The constructor function Foo is called with the specified arguments, and with this bound to the newly created object. | |
* new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments. | |
* 3. The object returned by the constructor function becomes the result of the whole new expression. | |
* If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. | |
* (Normally constructors don't return a value, but they can choose to do so if they want to override | |
* the normal object creation process.)" | |
* | |
* Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new. | |
*/ | |
function my(className) { | |
var _prototype = className.prototype; | |
return { | |
create: function() { | |
/* | |
* `context` here will store a new empty object with | |
* its `.__proto__` property pointing to `className.prototype`. | |
*/ | |
var context = Object.create(_prototype); | |
return className.apply(context, arguments) || context; | |
} | |
}; | |
} | |
/* | |
* Logging custom implementation. | |
*/ | |
var cat2 = my(Cat).create('barz'); | |
console.log(cat2) // {bar: "barz"} | |
console.log(cat2.foo) // "hello" | |
console.log(cat2 instanceof Cat); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment