Last active
August 2, 2016 15:47
-
-
Save sirbrillig/288a52bdfc299e511061f88ba1c2c1ff to your computer and use it in GitHub Desktop.
Two different ways to add a method to an object without mutating the object prototype
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
"use strict" | |
class OriginalObj { | |
sayHello() { | |
console.log( 'hello' ); | |
} | |
} | |
const myOriginal = new OriginalObj(); | |
myOriginal.sayHello(); | |
class AdvancedObj extends OriginalObj { | |
sayGoodbye() { | |
console.log( 'bye' ); | |
} | |
} | |
const myAdvanced = new AdvancedObj(); | |
myAdvanced.sayHello(); | |
myAdvanced.sayGoodbye(); | |
function wrapObj( original ) { | |
original.sayGoodbye = function sayGoodbye() { | |
console.log( 'bye' ); | |
} | |
return original; | |
} | |
const myWrapper = wrapObj( new OriginalObj() ); | |
myWrapper.sayHello(); | |
myWrapper.sayGoodbye(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment