Skip to content

Instantly share code, notes, and snippets.

@dayitv89
Last active September 5, 2022 16:37
Show Gist options
  • Save dayitv89/bdba93143e584830d6aaf4f79f20f21b to your computer and use it in GitHub Desktop.
Save dayitv89/bdba93143e584830d6aaf4f79f20f21b to your computer and use it in GitHub Desktop.
Prototype constructor in javascript / node.js
//node A.js > output.txt
// If Rabbit had any custom properties on it
// (or static properties as some call it), they would not be copied, you'd have to do that manually using getOwnPropertyNames
// ref: https://stackoverflow.com/a/9267343/1084917
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames
// var oldProto = Rabbit.prototype;
// Rabbit = function() {...};
// Rabbit.prototype = oldProto;
class A {
constructor(name) {
this.name = name;
}
print() {
console.log(this.name);
return this.name;
}
}
const a = new A('Gaurav');
a.print();
// override constructor
const oldProto = A.prototype;
A = function (name) {
this.name = 'Hello ' + name;
};
A.prototype = oldProto;
const b = new A('Mehul');
b.print();
Gaurav
Hello Mehul
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment