Skip to content

Instantly share code, notes, and snippets.

@gregtatum
Last active August 29, 2015 14:12
Show Gist options
  • Select an option

  • Save gregtatum/28ab12e184ba8eb3b2b9 to your computer and use it in GitHub Desktop.

Select an option

Save gregtatum/28ab12e184ba8eb3b2b9 to your computer and use it in GitHub Desktop.
newOperator function
/*
* This is an illustration of the new Object() functionality for JavaScript written
* as a function.
*/
function extend(a, b) {
var c = {}, attr;
for (attr in a) {
if (Object.prototype.hasOwnProperty.call(a, attr)) {
c[attr] = a[attr];
}
}
for (attr in b) {
if (Object.prototype.hasOwnProperty.call(b, attr)) {
c[attr] = b[attr];
}
}
return c;
}
function newOperator( func, proto, args ) {
var instance = extend( {}, proto );
func.apply( instance, args );
return instance;
};
function LoggerClass( message ) {
console.log('Creating new Logger');
this.message = message;
this.count = 0;
}
var prototype = {
log: function() {
this.count++;
console.log( this.count, this.message );
}
};
var arguments = ["hello"];
var logger = newOperator( LoggerClass, prototype, arguments );
// >>> Creating new object
logger.log();
// >> 1, hello
logger.log();
// >> 2, hello
logger.message = "Goodbye";
logger.log();
// >> 3, Goodbye
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment