Skip to content

Instantly share code, notes, and snippets.

@getify
Last active August 17, 2016 23:51
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/9895188 to your computer and use it in GitHub Desktop.
Save getify/9895188 to your computer and use it in GitHub Desktop.
composition vs. delegation
// 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
// 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
@ljharb
Copy link

ljharb commented Mar 31, 2014

With shimmed ES6 hotness you could do this:

var obj2 = Object.assign(Object.create(obj1), {
    id: "obj2",
    myId: function() { return this.id; },
    doAnother: function() {
        this.doSomething();
    }
});

Update: See my standalone Object.assign shim for lots of awesome examples, like [source1, source2, sourceN].reduce(Object.assign, target);!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment