I have 2 questions about functions inside object literals. I have included the workarounds I've been using, but they seem hackish. Is there a better way to do this?
ns = {
a: function (x, y) { return x+y; },
// Problem 1
// This does not work: Error: ns.b is not a function
b: this.a,
// Is this the correct workaround for this?
c: function (x, y) { return this.a(x, y); },
// Problem 2
// I understand why this won't work, because a is not defined in d's scope
d: function (x, y) {
function add(n, o) {
return this.a(n, o);
}
return add(3, 4);
},
// Is this the correct workaround for this? It works in Firefox and Chrome.
e: function (x, y) {
function add(n, o) {
return ns.a(n, o);
}
return add(3, 4);
}
};
ns.a(3, 4); //===> 7
ns.b(3, 4); //===> Error: ns.a is not a function
ns.c(3, 4); //===> 7
ns.d(3, 4); //===> Error: no method named a
ns.e(3, 4); //===> 7
EDIT: Thank you for all your replies. As missingno pointed out I am using ns to define a module, though I avoided the module pattern because I don't have any private variables. The following seems to be an elegant solution to my problems.
var ns = {};
ns.a = function (x, y) { return x+y; };
ns.b = ns.a;
ns.c = function (x, y) {
function add(n, o) {
return ns.a(3, 4);
}
return add(x, y);
}
ns.a(3, 4); //===> 7
ns.b(3, 4); //===> 7
ns.c(3, 4); //===> 7
Since this has been moved to Code Review, I'd welcome any critiques of my implementation of Scheme's SRFI-1.