Last active
July 28, 2024 18:03
-
-
Save ppraksa/2c39b1887f47805118b5a2c4464e1d6b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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