I'm working on a file manager framework similar to elFinder. My current code works fine but now I want to make it look better and add chaining (I'm not sure if it's chaining or decorator pattern).
Here is a sample of what I want to do:
function UI() {}
UI.prototype.folders = function(){
return [];
}
UI.prototype.folders.prototype.getSelectedFolder = function(){
return {};
}
Calling UI.folders() should return an array of folder objects. So if you call UI.folders() you would get something similar to this:
[
Object { name="folder1", selected=false },
Object { name="folder2", selected=false },
Object { name="folder3", selected=true }
]
And calling UI.folders().getSelectedFolder() would filter the results from UI.folders() and will return:
Object { name="folder3", selected=true }
Is this possible? Is it right to say "chaining" in this case or it's "decorative pattern"?
If it's not - is there another more appropriate way to do it?
Any help wold be really appreciated!
The code in your question isn't reflective of a proper implementation, but to answer your direct questions, yes, this...
UI.folders().getSelectedFolder()
...would be an example of method chaining.
A decorator pattern is different. If you have a set of methods, and each one should always first invoke some common function, you can create a decorator that will return a function that first calls the common one, then the actual one...
function foo() {
console.log('I\'m foo, and I\'m first, and I was given these args:', arguments);
}
function decorateWithFoo(decorated) {
return function () {
foo.apply(this, arguments);
decorated.apply(this, arguments);
};
}
So you can use decorateWithFoo to create a function that always invokes foo first...
// create and decorate bar()
var bar = function(a,b) {
console.log('I\'m bar, and I was called after "foo", and was given args:', a, b);
};
bar = decorateWithFoo(bar);
bar(123, 456); // this will first call `foo()`, then (the original) `bar()`.
// create and decorate baz()
var baz = function(a,b) {
console.log('I\'m baz, and I was called after "foo", and was given args:', a, b);
};
baz = decorateWithFoo(baz);
baz(123, 456); // this will first call `foo()`, then (the original) `baz()`.
Some languages have built in syntax for creating decorators. JavaScript currently does not.
If you find yourself using decorators in different ways, you could create another function that sets up the initial decorator function...
function generateDecorator(decorator) {
return function (decorated) {
return function () {
decorator.apply(this, arguments);
decorated.apply(this, arguments);
};
};
}
So our original decoreateWithFoo could have been set up like this...
function foo() {
console.log('I\'m foo, and I\'m first, and I was given these args:', arguments);
}
var decorateWithFoo = generateDecorator(foo);
To make this work properly, you need to make your folders method be a function that returns an object that inherits from an array.:
UI.prototype.folders = function(){
// must return an object that inherits from an array
// that has the additional methods on it you want like getSelectedFolder()
}
The are a few different ways to solve this. The primary goal is that when you call a function you get an object/function back that is the same type of object with different properties. I'm not a fan of the prototype usage so I would do it like this (this is one way to solve it):
var FolderList = function ()
{
var _folders = [];
folders.pop({ name: "folder1", selected: false });
folders.pop({ name: "folder2", selected: true });
folders.pop({ name: "folder3", selected: false });
// prevent other programers from changing _folders
// which would break this, so just use a function
this.folders = function ()
{
return _folders;
}
this.selectedFolders = function ()
{
var tmpFolders = [];
for (var folderIndex = 0;
folderIndex < this._folders.length;
folderIndex++)
{
if (this._folders[folderIndex].selected)
{
tmpFolders.pop(_folders[folderIndex]);
}
}
_folders = tmpFolders;
return this;
}
this.addFolder = function (folder)
{
_folders.pop(folder);
return this;
}
};
var folderList = new FolderList();
folderList.selectedFolders()
.addFolder({ name: "folder1", selected: false })
.addFolder({ name: "folder3", selected: true })
.selectedFolders();
// array of 2 objects, folder2 and folder3
var arrayOfSelectedFolder = folderList.folders();
Related
I want to export one variable after initialized by parameters from one module in Node.js.
Now, there are three options for me.
Option 1: with exports directly
// moduletest.js
exports.init = function(v, w) {
// actually, the value of a and b could be initialized by other functions.
// here is one example, simply assign them with v and w just for test
exports.a = v;
exports.b = w;
}
The variable a and b could be used out of the module.
// app.js
require('./moduletest').init(3, 1);
var ff = require('./moduletest');
console.log(ff.a);
console.log(ff.b);
Option 2: var one get method in the object.
var MyObject = {
init: function(a, b) {
this._a_ = a;
this._b_ = b;
},
getA: function () {
return this._a_;
},
};
exports.mod = {
valA: MyObject.getA,
init: MyObject.init
}
The variable _a_ could be accessed by getA method.
Option 3: through one get method in the function prototype.
var Test = function (a, b){
this._a_ = a;
this._b_ = b;
};
Test.prototype.getA = function()
{
return this._a_;
}
exports.mod = Test;
Here I have two questions:
Which one is more elegant way to do that?
If none of above three options is better, is there any better ways?
Based on the comments to your question, a possible approach is the one below. Yours have mainly the problem that you don't actually hide the data, thus letting the user to modify them.
module.exports = function (_a, _b) {
return function() {
var obj = { };
Object.defineProperty(obj, 'a', {
get: function () { return _a; }
});
Object.defineProperty(obj, 'b', {
get: function () { return _b; }
});
};
}
You can use it as it follows:
var factory = require('file_above')(your_a, your_b);
// code
var instance = factory();
// you cannot modify a or b on instance!!
Something similar can be done by using the bind method of a function and so on. Keep in mind that there is a plenty of possible solutions and none of them is the right one, while almost all of them are valid ones.
As far as I see, anyway, the ones you posted above have some minor issues, even though all of them work fine, of course.
I want to store a function, internal to the function-object its within, in an object member, but I need to get access to it via name. The code below makes it easier to understand...
// MyClassThing.js:
var MyClassThing = (function() {
var _ref = {obj: undefined, fnc: undefined};
function setup(domObject, refName) {
_ref.obj = domObject;
_ref.fnc = this['func_' + refName]; // <<-- This does not work!!
}
function doThing() {
if(_ref.func)
_ref.fnc();
}
function func_foo() {
console.log('Foo!');
}
return {
setup: setup,
doThing: doThing
};
})();
// index.html
<script>
MyClassThing.setup($('#fooObj'), 'foo');
MyClassThing.doThing();
</script>
What do I do to get _ref.fnc = ???? to work properly?
You will have to use helper object to put methods as its properties. Then you will be able to refer to them by variable name:
var MyClassThing = (function () {
var _ref = { obj: undefined, fnc: undefined },
methods = {};
function setup(domObject, refName) {
_ref.obj = domObject;
_ref.fnc = methods['func_' + refName];
}
function doThing () {
if (_ref.fnc) _ref.fnc();
}
methods.func_foo = function () {
console.log('Foo!');
};
return {
setup: setup,
doThing: doThing
};
})();
You can't use this because it points to the object returned from IIFE, however your methods of interest are not properties of this object.
There's a typo in your code:
var MyClassThing = (function() {
var _ref = {obj: undefined, fnc: undefined};
function setup(domObject, refName) {
_ref.obj = domObject;
_ref.fnc = this['func_' + refName]; // <<-- This does not work!!
}
function doThing() {
if(_ref.fnc)
_ref.fnc();
}
function func_foo() {
console.log('Foo!');
}
return {
setup: setup,
doThing: doThing
};
})();
In your doThing function, you are checking for the existency of a _ref.func instead of _ref.fnc
To achieve what you want to do, you need to understand that the functions you are declaring using the "function" are not linked to the class. There's no notion of "private member function" in javascript. If you want to bind a function to a class, you need to declare it like this (there are other ways, i'm just showing you one of them) :
MyClassThing.prototype.func_foo = function () {
}
The best thing to do, in your case, would be to set _ref.fnc to func_foo directly. If you want to keep the this context, take a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 9 years ago.
I have 2 BI object in different files, now I want to extend the first object with other ones.
1st Object
var BI = BI || {};
BI = {
firstInit: function () {
console.log('I am first init');
}
}
Other file
2nd Object
BI = {
init: function () {
console.log('I am init');
}
}
Now I want 2nd Object should contain the firstInit as well. Let me know I can explain further. I am using jQuery.
You can use jQuery's $.extend here.
Try following code
var BI = BI || {};
BI = {
firstInit: function () {
console.log('I am first init');
}
}
$.extend(BI, {
init: function () {
console.log('I am init');
}
});
console.log(BI);
Here is the DEMO
Out of the box, you can't do it that easily with good x-browser support.
However, jQuery does give you a means to have objects extend eachother: http://api.jquery.com/jQuery.extend/
So you would do:
var extended = $.extend({}, BI, {
init: function () {
console.log('I am init');
}
});
The first argument (empty object, {}) means that the properties of BI (the second argument) and the object you pass in will be combined in to the new object.
I wrote a small polymorphic extension to $.extend for this purpose which will allow you to extend from multiple objects, with the latter item taking precidence:
mergeObjects = function () {
// Convert the arguments Array-like object to an actual array
var args = Array.prototype.slice.call(arguments);
// Only one item? If we give this to $.extend it'll extend jQuery, which is
// not the desired result, so let's spit it back verbatim
if (args.length === 1) {
return args[0];
}
// We need to make sure we're always combining objects starting with a
// completely empty one
args.unshift(true, {});
return jQuery.extend.apply(jQuery, args);
};
So, you can define your base module with common properties like so:
var MyBaseModule.prototype = {
options: {},
getOptions: function () {
return this.options || {};
},
setOptions: function (options) {
this.options = options;
},
log: function () {
// do your logging stuff here
},
error: function () {
// do your error handling stuff here
}
};
And your actual modules:
var MyModule = function () {
// constructor code here
};
var MyModule.prototype = mergeObjects(MyBaseModule, {
// define your module's methods here
});
...now MyModule has "inherited" the options property and options getter and setter. You can instantiate the new module with new MyModule;
If you want a vanilla way of doing it, this post may be useful
There are 2 ways of doing this in JavaScript. One is using prototype chaining, the other is to just copy the method. In this case both of your objects have the object as the prototype, so you need to copy the method:
BI2.init = BI1.firstInit;
To copy all methods and attributes in JQuery, use $.extend;
BI2 = $.extend({ init: function () { } }, BI1);
In Javascript Functions are objects. So they can be passed as arguments to functions or assigned to other variables (referenced).
var BI = {
firstInit: function () {
console.log('I am first init');
}
};
var BI2 = {
init: function () {
console.log('I am init');
}
}
// copy the reference of function
BI2.originalFirstInit = BI.firstInit;
// run this function
BI2.originalFirstInit(); // output: "I am first init"
This is something which has been bugging me with the Google Chrome debugger and I was wondering if there was a way to solve it.
I'm working on a large Javascript application, using a lot of object oriented JS (using the Joose framework), and when I debug my code, all my classes are given a non-sensical initial display value. To see what I mean, try this in the Chrome console:
var F = function () {};
var myObj = new F();
console.log(myObj);
The output should be a single line which you can expand to see all the properties of myObj, but the first thing you see is just ▶ F.
My issue is that because of my OO framework, every single object instantiated gets the same 'name'. The code which it looks is responsible for this is like so:
getMutableCopy : function (object) {
var f = function () {};
f.prototype = object;
return new f();
}
Which means that in the debugger, the initial view is always ▶ f.
Now, I really don't want to be changing anything about how Joose instantiates objects (getMutableCopy...?), but if there was something I could add to this so that I could provide my own name, that would be great.
Some things that I've looked at, but couldn't get anywhere with:
> function foo {}
> foo.name
"foo"
> foo.name = "bar"
"bar"
> foo.name
"foo" // <-- looks like it is read only
Object.defineProperty(fn, "name", { value: "New Name" });
Will do the trick and is the most performant solution. No eval either.
I've been playing around with this for the last 3 hours and finally got it at least somewhat elegant using new Function as suggested on other threads:
/**
* JavaScript Rename Function
* #author Nate Ferrero
* #license Public Domain
* #date Apr 5th, 2014
*/
var renameFunction = function (name, fn) {
return (new Function("return function (call) { return function " + name +
" () { return call(this, arguments) }; };")())(Function.apply.bind(fn));
};
/**
* Test Code
*/
var cls = renameFunction('Book', function (title) {
this.title = title;
});
new cls('One Flew to Kill a Mockingbird');
If you run the above code, you should see the following output to your console:
Book {title: "One Flew to Kill a Mockingbird"}
Combine usage of computed property name to dynamically name a property, and inferred function naming to give our anonymous function that computed property name:
const name = "aDynamicName"
const tmp = {
[name]: function(){
return 42
}
}
const myFunction= tmp[name]
console.log(myFunction) //=> [Function: aDynamicName]
console.log(myFunction.name) //=> 'aDynamicName'
One could use whatever they want for 'name' here, to create a function with whatever name they want.
If this isn't clear, let's break down the two pieces of this technique separately:
Computed Property Names
const name = "myProperty"
const o = {
[name]: 42
}
console.log(o) //=> { myProperty: 42 }
We can see that the property name assigned on o was myProperty, by way of computed property naming. The []'s here cause JS to lookup the value inside the bracket, and to use that for the property name.
Inferred Function Naming
const o = {
myFunction: function(){ return 42 }
}
console.log(o.myFunction) //=> [Function: myFunction]
console.log(o.myFunction.name) //=> 'myFunction'
Here we use inferred function naming. The language looks at the name of wherever the function is being assigned to, & gives the function that inferred name.
We can combine these two techniques, as shown in the beginning. We create an anonymous function, which gets it's name via inferred function naming, from a computed property name, which is the dynamic name we wanted to create. Then we have to extract the newly created function from the object it is embedded inside of.
Example Using Stack Trace
Naming a supplied anonymous function
// Check the error stack trace to see the given name
function runAnonFnWithName(newName, fn) {
const hack = { [newName]: fn };
hack[newName]();
}
runAnonFnWithName("MyNewFunctionName", () => {
throw new Error("Fire!");
});
Although it is ugly, you could cheat via eval():
function copy(parent, name){
name = typeof name==='undefined'?'Foobar':name;
var f = eval('function '+name+'(){};'+name);
f.prototype = parent;
return new f();
}
var parent = {a:50};
var child = copy(parent, 'MyName');
console.log(child); // Shows 'MyName' in Chrome console.
Beware: You can only use names which would be valid as function names!
Addendum: To avoid evaling on every object instantiation, use a cache:
function Cache(fallback){
var cache = {};
this.get = function(id){
if (!cache.hasOwnProperty(id)){
cache[id] = fallback.apply(null, Array.prototype.slice.call(arguments, 1));
}
return cache[id];
}
}
var copy = (function(){
var cache = new Cache(createPrototypedFunction);
function createPrototypedFunction(parent, name){
var f = eval('function '+name+'(){};'+name);
f.prototype = parent;
return f;
}
return function(parent, name){
return new (cache.get(name, parent, typeof name==='undefined'?'Foobar':name));
};
})();
This won't totally solve your problem, but I would suggest overriding the toString method on the class's prototype. For instance:
my_class = function () {}
my_class.prototype.toString = function () { return 'Name of Class'; }
You'll still see the original class name if you enter an instance of my_class directly in the console (I don't think it's possible to do anything about this), but you'll get the nice name in error messages, which I find very helpful. For instance:
a = new my_class()
a.does_not_exist()
Will give the error message: "TypeError: Object Name of Class has no method 'does_not_exist'"
If you want to dynamically create a named function. You can use new Function to create your named function.
function getMutableCopy(fnName,proto) {
var f = new Function(`function ${fnName}(){}; return ${fnName}`)()
f.prototype = proto;
return new f();
}
getMutableCopy("bar",{})
// ▶ bar{}
Similar to #Piercey4 answer, but I had to set the name for the instance as well:
function generateConstructor(newName) {
function F() {
// This is important:
this.name = newName;
};
Object.defineProperty(F, 'name', {
value: newName,
writable: false
});
return F;
}
const MyFunc = generateConstructor('MyFunc');
const instance = new MyFunc();
console.log(MyFunc.name); // prints 'MyFunc'
console.log(instance.name); // prints 'MyFunc'
normally you use window[name] like
var name ="bar";
window["foo"+name] = "bam!";
foobar; // "bam!"
which would lead you to a function like:
function getmc (object, name) {
window[name] = function () {};
window[name].prototype = object;
return new window[name]();
}
but then
foo = function(){};
foobar = getmc(foo, "bar");
foobar; // ▶ window
foobar.name; // foo
x = new bar; x.name; // foo .. not even nija'ing the parameter works
and since you can't eval a return statement (eval("return new name()");), I think you're stuck
I think this is the best way to dynamically set the name of a function :
Function.prototype.setName = function (newName) {
Object.defineProperty(this,'name', {
get : function () {
return newName;
}
});
}
Now you just need to call the setName method
function foo () { }
foo.name; // returns 'foo'
foo.setName('bar');
foo.name; // returns 'bar'
foo.name = 'something else';
foo.name; // returns 'bar'
foo.setName({bar : 123});
foo.name; // returns {bar : 123}
Based on the answer of #josh, this prints in a console REPL, shows in console.log and shows in the debugger tooltip:
var fn = function() {
return 1917;
};
fn.oldToString = fn.toString;
fn.toString = function() {
return "That fine function I wrote recently: " + this.oldToString();
};
var that = fn;
console.log(that);
Inclusion of fn.oldToString() is a magic which makes it work. If I exclude it, nothing works any more.
With ECMAScript2015 (ES2015, ES6) language specification, it is possible to dynamically set a function name without the use of slow and unsafe eval function and without Object.defineProperty method which both corrupts function object and does not work in some crucial aspects anyway.
See, for example, this nameAndSelfBind function that is able to both name anonymous functions and renaming named functions, as well as binding their own bodies to themselves as this and storing references to processed functions to be used in an outer scope (JSFiddle):
(function()
{
// an optional constant to store references to all named and bound functions:
const arrayOfFormerlyAnonymousFunctions = [],
removeEventListenerAfterDelay = 3000; // an auxiliary variable for setTimeout
// this function both names argument function and makes it self-aware,
// binding it to itself; useful e.g. for event listeners which then will be able
// self-remove from within an anonymous functions they use as callbacks:
function nameAndSelfBind(functionToNameAndSelfBind,
name = 'namedAndBoundFunction', // optional
outerScopeReference) // optional
{
const functionAsObject = {
[name]()
{
return binder(...arguments);
}
},
namedAndBoundFunction = functionAsObject[name];
// if no arbitrary-naming functionality is required, then the constants above are
// not needed, and the following function should be just "var namedAndBoundFunction = ":
var binder = function()
{
return functionToNameAndSelfBind.bind(namedAndBoundFunction, ...arguments)();
}
// this optional functionality allows to assign the function to a outer scope variable
// if can not be done otherwise; useful for example for the ability to remove event
// listeners from the outer scope:
if (typeof outerScopeReference !== 'undefined')
{
if (outerScopeReference instanceof Array)
{
outerScopeReference.push(namedAndBoundFunction);
}
else
{
outerScopeReference = namedAndBoundFunction;
}
}
return namedAndBoundFunction;
}
// removeEventListener callback can not remove the listener if the callback is an anonymous
// function, but thanks to the nameAndSelfBind function it is now possible; this listener
// removes itself right after the first time being triggered:
document.addEventListener("visibilitychange", nameAndSelfBind(function(e)
{
e.target.removeEventListener('visibilitychange', this, false);
console.log('\nEvent listener 1 triggered:', e, '\nthis: ', this,
'\n\nremoveEventListener 1 was called; if "this" value was correct, "'
+ e.type + '"" event will not listened to any more');
}, undefined, arrayOfFormerlyAnonymousFunctions), false);
// to prove that deanonymized functions -- even when they have the same 'namedAndBoundFunction'
// name -- belong to different scopes and hence removing one does not mean removing another,
// a different event listener is added:
document.addEventListener("visibilitychange", nameAndSelfBind(function(e)
{
console.log('\nEvent listener 2 triggered:', e, '\nthis: ', this);
}, undefined, arrayOfFormerlyAnonymousFunctions), false);
// to check that arrayOfFormerlyAnonymousFunctions constant does keep a valid reference to
// formerly anonymous callback function of one of the event listeners, an attempt to remove
// it is made:
setTimeout(function(delay)
{
document.removeEventListener('visibilitychange',
arrayOfFormerlyAnonymousFunctions[arrayOfFormerlyAnonymousFunctions.length - 1],
false);
console.log('\nAfter ' + delay + 'ms, an event listener 2 was removed; if reference in '
+ 'arrayOfFormerlyAnonymousFunctions value was correct, the event will not '
+ 'be listened to any more', arrayOfFormerlyAnonymousFunctions);
}, removeEventListenerAfterDelay, removeEventListenerAfterDelay);
})();
I have not seen anyone mention the use of ES6 Proxies. Which in my opinion solve this problem beautifully. So here it is.
function shadow(object, secondObject) {
return new Proxy(object, {
get(target, prop, receiver) {
if (secondObject.hasOwnProperty(prop)) return secondObject[prop];
return Reflect.get(...arguments);
}
})
}
let t=function namedFunction(a,b,c){return a+b+c;}
console.log(t.name)//read only property
let f=shadow(t,{name:"addition"})
console.log(f.name)
I have a bunch of functions (methods of a class actually) and I'm writing a method that will record the interactions with other methods in an array.
so for example :
foo = Base.extend ({
a : function (a1,a2){
....
},
b:function(b1,b2){
...
},
history : function(){ ... }
})
to simplify the history method, I'd like to read the name of the optional arguments and add them to the array, so for example if the method a is called, I want to record a1,a2 ...
so basically, is there any way to read the name of the optional arguments list of an array in javascript ?
here is the code :
var element = Base.extend({
constructor : function() {
if(arguments.length==1){
...
}else{
...
}
},
setLocation : function (top, left){
oldArgs = [this.top,this.left];
this.top = top;
this.left = left;
return(oldArgs);
},
setAspects : function (width, height){
oldArgs = [this.width,this.height]
this.width = width;
this.height = height;
return(oldArgs);
},
draw : function (page){
...
},
delet : function () {
...
},
$ : function(method,args){
var oldArgs = this[method].apply(this,args);
this.history(method,oldArgs);
Nx.pages[this.page].modified = true;
},
history : function (method,args){
Nx.history[Nx.history.length]=[this.id,method,args]
}
})
so in this class, if I want to call any method, I'll pas it through the $ method, and it will call the history method, so far what I've done is for example in the setLocation method it will return the old arguments and I will story them in my array Nx.history, but it's easier to factorise all of these "return" calls in the methods, and add a line to the $ method , that reads the name of the expected arguments of the method, and send it to the history method, so something like this :
$ : function(method,args){
this[method].apply(this,args);
**var oldArgs = this[method].arguments // get the list of argument names here
$.each(oldArgs, function(value) { Args[Args.length] = this.value //get the stored value in the class
})
this.history(method,Args); // and pass it to the history**
Nx.pages[this.page].modified = true;
}
I'm not 100% sure what you're asking for - a way to extract the formal parameter names of a function?
I have no idea if this would work or not, but could you parse the string representation of the function to extract the parameter names?
It would probably be a very lame solution, but you might be able to do something like:
function getArgNames(fn) {
var args = fn.toString().match(/function\b[^(]*\(([^)]*)\)/)[1];
return args.split(/\s*,\s*/);
}
2.0
The idea with this newer version is to define the properties that you want to record for the object beforehand. It's a level of duplication, but it's only a one time thing. Then, in the constructor, create property setters for each of these properties. The setter does some side work along with setting the property. It pushes the arguments name and value onto a stack, and assigns the properties. The $ method is supposed to call dispatch the call to the appropriate method. Once the call is complete, the stack will be populated with the parameters that were set in that function. Pop off each parameter from that stack, until the stack is empty. Then call history with the method name, and the parameters that we just popped off the stack. Please let me know if this doesn't make any sense, I might have to word it better.
See an example here.
Here's a code example written in MooTools which is slightly similar to your Base class.
var Device = new Class({
_properties: ['top', 'left', 'width', 'height'],
_parameterStack: [],
initialize: function() {
this._createPropertyAccessors();
},
_createPropertyAccessors: function() {
this._properties.each(function(property) {
Object.defineProperty(this, property, {
enumerable: true,
configurable: true,
set: function(value) {
var o = {};
o[property] = value;
// push the parameter onto the stack
this._parameterStack.push(o);
}.bind(this)
});
}.bind(this));
},
// method stays unchanged
setLocation: function(top, left) {
this.top = top;
this.left = left;
},
setAspects: function(width, height) {
this.width = width;
this.height = height;
},
// dispatches call to method
// pops off the entire stack
// passed method name, and emptied stack arguments to history
$: function(method, args) {
this[method].apply(this, args);
var argsStack = [];
while(this._parameterStack.length) {
argsStack.push(this._parameterStack.pop());
}
this.history(method, argsStack);
},
history: function(method, args) {
console.log("%s(%o) called", method, args);
}
});
1.0
The arguments passed to a JavaScript function are accessible through an array-like object named arguments which is available for all functions.
When calling history, pass the arguments object to it.
a: function(a1, a2) {
this.history.apply(this, arguments);
}
history will then be invoked as if it was called with two arguments with this being the base object - foo unless you call it with a different context.
I am not sure how Base plays into this. You would have to elaborate more as to the role of Base here.
Here' s a simple example:
var foo = {
a: function(a1, a2) {
this.history.apply(this, arguments);
},
history: function() {
console.log("history received " + arguments.length + " arguments.");
}
};
foo.a("hello", "world"); // history received 2 arguments
Also note that although a has two named parameters here, we can still pass it any number of arguments, and all of them will be passed to the history method in turn. We could call a as:
foo.a(1, 2, 3); // history received 3 arguments
Something like this should work. When you want to access the arguments that have been used you can loop through the foo.history array which contains the arguments list.
var foo = {
storeArgs: function (fn) {
return function() {
this.history += arguments
return fn.apply(null, arguments);
}
},
a: storeArgs(function(a1, a2) {
alert(a1+a2);
}),
history: []
};
I read your updated post. What do you mean by "names?" Variable names? For example, if someone called a(1337), would you want ["a1"] to be added to the array? And if a(1337, 132) was called ["a1", "a2"] would be added? I don't think there's any sane way to do that.
This is the best I can do. You will have to include a list of parameter names when defining your functions using the storeArgs function.
var foo = {
storeArgs: function (params, fn) {
return function() {
var arr = [];
for (var i = 0; i < arguments.length; i++) {
arr.push(params[i]);
}
this.history += arr;
return fn.apply(null, arguments);
}
}
a: storeArgs(["a1", "a2"], function(a1, a2) {
alert(a1+a2);
}),
history: []
};
Let me know if it works.
This works in IE, but I'm not sure about other browsers...
Function.prototype.params = function() {
var params = this.toString().split(/(\r\n)|(\n)/g)[0];
params = params.trim().replace(/^function.*?\(/, "");
params = params.match(/(.*?)\)/)[1].trim();
if (!params) {
return([]);
}
return(params.split(/, /g));
};
function Test(a, b) {
alert(Test.params());
}
Test();