Skip to content

Instantly share code, notes, and snippets.

@winarcooo
Created April 13, 2019 17:24
Show Gist options
  • Save winarcooo/22d2956a854539600b5ddd8f276f4b63 to your computer and use it in GitHub Desktop.
Save winarcooo/22d2956a854539600b5ddd8f276f4b63 to your computer and use it in GitHub Desktop.
function Person(saying) {
this.saying = saying
}
Person.prototype.talk = function() {
console.log('I say:', this.saying);
}
// replicate what `new` does
function spawn(constructor) {
// 1. create a new object
var obj = {}
// 2. set the prototype
Object.setPrototypeOf(obj, constructor.prototype)
var argsArray = Array.prototype.slice.apply(arguments)
// 3. execute constructor with `this`
// 4. return the created object, unless the constructor return the object
return constructor.apply(obj, argsArray.slice(1)) || obj
}
var crockforg = spawn(Person, 'semicolans1!!')
crockforg.talk()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment