Skip to content

Instantly share code, notes, and snippets.

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) { = name
Student.prototype.greet = function () {
console.log("Hi, ",;
var nick = New (Student)("Nick");; // "Nick"
nick.greet(); // prints "Hi, Nick"
// Compare with:
var dave = new Student("Dave");; // "Dave"
dave.greet(); // prints "Hi, Dave"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment