What is the best way to copy but not clone a function in javascript? -
given have declared function in of foo = function f() {}
how can copy but not clone function. example code below each time 1 calls function log()
argument argument added array log.list
list can shown calling function log.alert()
.
how can 1 declare new variable log2
copy functionality of log
function remain independent of it?
i.e independent list
maintained log
, log2
, calling log2.alert()
log2.list
shown , calling log.alert()
log.list
shown?
var log = log || function f (x) { f.list = f.list || []; if (x != undefined) f.list.push(x); if (!f.fired) { f.alert = function () { alert (f.list.join("\n")); } f.reset = function () { f.list = []; } f.fired = true; } } // demonstrate function log("log #1"); log("log #2"); log("log #3"); log("log #4"); log.alert();
this ones bit tricky. you've half described factories, functions return new objects (including functions), , half described regular constructor, creates instances.
the crux of question whether or not directly invoking log
, log2
variables of real importance. javascript doesn't offer way meta-call non-function objects, , looks es6 proxies
skipped on implementing functionality (you can intercept invocations of functions). real way invoke log
if is function.
you define factory function returns function appropriate methods attached directly it, , encapsulate variables need. overhead involved pattern have redefine function , 2 methods every time create new 'log'.
function logfactory () { var stack = []; function f () { stack.push.apply(stack, arguments); } f.list = stack; f.alert = function () { alert(stack); }; f.reset = function () { while (stack.length > 0) { stack.pop(); } }; return f; } var log = logfactory(), log2 = logfactory(); log('one', 'three'); log2('two', 'four'); log.alert(); log.reset(); log2.alert(); alert('lists different? ' + log.list !== log2.list);
however, if don't need invoke log
object directly, can create normal constructor prototype methods, , drop overhead.
function log () { this.list = []; } log.prototype.add = function () { this.list.push.apply(this.list, arguments); }; log.prototype.alert = function () { alert(this.list); }; log.prototype.reset = function () { while (this.list.length > 0) { this.list.pop(); } }; var log = new log(), log2 = new log(); log.add('one', 'three'); log2.add('two', 'four'); log.alert(); log.reset(); log2.alert(); alert('lists different? ' + log.list !== log2.list);
it should noted in example, function f
redefining own methods every time invoked push list
. that's undesirable.
Comments
Post a Comment