Last active
August 17, 2016 23:51
-
-
Save getify/9895188 to your computer and use it in GitHub Desktop.
composition vs. delegation
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
// composition | |
var obj1 = { | |
doSomething: function(myId) { | |
console.log( "Something: " + myId() ); | |
} | |
}; | |
var obj2 = { | |
id: "obj2", | |
obj1: obj1, | |
myId: function() { return this.id; }, | |
doAnother: function() { | |
obj1.doSomething( this.myId.bind(this) ); | |
} | |
}; | |
obj2.doAnother(); // Something: obj2 |
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
// delegation | |
var obj1 = { | |
doSomething: function() { | |
console.log( "Something: " + this.myId() ); | |
} | |
}; | |
var obj2 = { | |
id: "obj2", | |
myId: function() { return this.id; }, | |
doAnother: function() { | |
this.doSomething(); | |
} | |
}; | |
// link for delegation | |
obj2.__proto__ = obj1; | |
// NOTE per @ljharb: __proto__ is discouraged in favor of `Object.setPrototypeOf(..)` | |
// Object.setPrototypeOf( obj2, obj1 ); | |
// Also, could have created `obj2` with the link, like: | |
// var obj2 = Object.create( obj1 ); | |
// Downside is we lose the nicer object-literal syntax. :/ | |
obj2.doAnother(); // Something: obj2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With shimmed ES6 hotness you could do this:
Update: See my standalone
Object.assign
shim for lots of awesome examples, like[source1, source2, sourceN].reduce(Object.assign, target);
!