Skip to content

Instantly share code, notes, and snippets.

@ppraksa
Last active July 28, 2024 18:03
Show Gist options
  • Select an option

  • Save ppraksa/2c39b1887f47805118b5a2c4464e1d6b to your computer and use it in GitHub Desktop.

Select an option

Save ppraksa/2c39b1887f47805118b5a2c4464e1d6b to your computer and use it in GitHub Desktop.
function Person(name) {
console.log("old constructor");
let obj;
// Another time just return obj above
Person = function Person() {
console.log("new constructor");
return obj;
};
// set proper prototype (new instance)
Person.prototype = this;
// Call the old constructor from line 1
obj = new Person(name);
// set new Constructor from line 7
obj.constructor = Person;
// Do some logic
this.name = name;
// First time return instance by old constructor
return obj;
}
var test = new Person("Dandy boy");
var test2 = new Person("Dandy horse");
Person.prototype.getName = function () {
console.log(this.name);
};
test.getName();
test2.getName();
console.log(test instanceof Person);
console.log(test2 instanceof Person);
console.log(test === test2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment