Skip to content

Instantly share code, notes, and snippets.

@syntacticsugar
Forked from nicholasbs/gist:3259846
Created November 8, 2012 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syntacticsugar/4041425 to your computer and use it in GitHub Desktop.
Save syntacticsugar/4041425 to your computer and use it in GitHub Desktop.
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");
// 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