Created
February 3, 2016 08:09
-
-
Save mathieuancelin/8bdba6b630b3aaf4899d 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(firstName: string, lastName: string, age: number) { | |
if (!this) return new Person(firstName, lastName, age); // if no new, then new to have type | |
return Object.freeze(Object.assign(this || {}, { // assign is use of enhance this, to have type | |
copy(obj) { | |
const values = { firstName, lastName, age, ...obj }; | |
return new Person(values.firstName, values.lastName, values.age); | |
}, | |
get firstName() { | |
return firstName; | |
}, | |
get lastName() { | |
return lastName; | |
}, | |
get age() { | |
return age; | |
}, | |
toString() { | |
return `Person(${firstName}, ${lastName}, ${age})`; | |
} | |
})); | |
} | |
const person1 = Person('John', 'DOE', 42) | |
const person2 = new Person('Jane', 'DOE', 42); | |
const person3 = person1 | |
.copy({ firstName: 'Billy' }) | |
.copy({ age: '28' }); | |
console.log(person1.toString()); | |
console.log(person2.toString()); | |
console.log(person3.toString()); | |
person1.hello = 'hello'; // will not work | |
person1.firstName = 'Eugene'; // will not work |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment