-
-
Save dayitv89/bdba93143e584830d6aaf4f79f20f21b to your computer and use it in GitHub Desktop.
Prototype constructor in javascript / node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Gaurav | |
Hello Mehul |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment