-
-
Save syntacticsugar/4041425 to your computer and use it in GitHub Desktop.
Implementing the "new" operator in JavaScript
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
// New is a function that takes a function F | |
function New (F) { | |
var o = {}; // and creates a new object o | |
o.__proto__ = F.prototype // and sets o.__proto__ to be F's prototype | |
// New returns a function that... | |
return function () { | |
F.apply(o, arguments); // runs F with o as "this", passing along any arguments | |
return o; // and returns o, the new object we created | |
} | |
} | |
// Example usage | |
function Student (name) { | |
this.name = name | |
} | |
Student.prototype.greet = function () { | |
console.log("Hi, ", this.name); | |
} | |
var nick = New (Student)("Nick"); | |
// var nick = (New(Student))("Nick"); // the same! | |
nick.name; // "Nick" | |
nick.greet(); // prints "Hi, Nick" | |
// Compare with: | |
var dave = new Student("Dave"); | |
dave.name; // "Dave" | |
dave.greet(); // prints "Hi, Dave" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment