Skip to content

Instantly share code, notes, and snippets.

@tauren
Last active December 31, 2015 16:39
Show Gist options
  • Save tauren/8015512 to your computer and use it in GitHub Desktop.
Save tauren/8015512 to your computer and use it in GitHub Desktop.
Looking for a way to apply AOP before, after, or around functions to an object constructor.
// Sipmle AOP after function
var after = function(base, after) {
if (!base) {
return after;
}
return function composedAfter() {
var res = base.apply(this, arguments);
after.apply(this, arguments);
return res;
};
};
// Functional mixin to add the talk feature to an object
var withTalk = function(destination) {
destination.talkConstructor = function() {
console.log('Constructing talker '+this.name);
};
destination.talk = function() {
console.log('My name is '+this.name);
};
destination.init = after(destination.init, function() {
console.log('Initializing talker '+this.name);
});
console.log('Talk feature added to destination');
};
console.log('\n-----------FOO----------');
// Augmentation of init function
function Foo (name) {
console.log('Constructing foo '+name);
this.name = name;
}
Foo.prototype.init = function() {
console.log('Initializing foo '+this.name);
};
// Mix the Talk feature into Foo
withTalk(Foo.prototype);
var foo = new Foo('Timon');
foo.init();
foo.talk();
console.log('\n-----------BAR----------');
// Augmentation of constructor
// PROBLEM: Requires talkConstructor to be called from constructor
function Bar (name) {
console.log('Constructing bar '+name);
this.name = name;
// OBJECTIVE: How can this call be removed?
this.talkConstructor();
}
Bar.prototype.init = function() {
console.log('Initializing bar '+this.name);
};
// Mix the Talk feature into Bar
withTalk(Bar.prototype);
var bar = new Bar('Pumba');
bar.init();
bar.talk();
/*
The following output is generated:
-----------FOO----------
Talk feature added to destination
Constructing foo Timon
Initializing foo Timon
Initializing talker Timon
My name is Timon
-----------BAR----------
Talk feature added to destination
Constructing bar Pumba
Constructing talker Pumba
Initializing bar Pumba
Initializing talker Pumba
My name is Pumba
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment