Skip to content

Instantly share code, notes, and snippets.

@sirbrillig
Last active August 2, 2016 15:47
Show Gist options
  • Save sirbrillig/288a52bdfc299e511061f88ba1c2c1ff to your computer and use it in GitHub Desktop.
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
"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