Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Implementing the "new" operator in JavaScript
// 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");
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
You can’t perform that action at this time.