patternjavascriptMinor
Functions in object literals
Viewed 0 times
literalsfunctionsobject
Problem
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?
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.
Since this has been moved to Code Review, I'd welcome any critiques of my implementation of Scheme's SRFI-1.
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); //===> 7EDIT: 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); //===> 7Since this has been moved to Code Review, I'd welcome any critiques of my implementation of Scheme's SRFI-1.
Solution
Problem 1
Just assign them one at a time, once the object already exists:
To answer specifically whether there's any other workaround if you're dead set on declaring these inside the object literal syntax: no.
Problem 2
Looks good enough to me, though I'd try to avoid using the object's name so deep into its definition.
Consider using prototyping instead.
Just assign them one at a time, once the object already exists:
ns = {};
ns.a = function (x, y) { return x+y; };
ns.b = ns.a;To answer specifically whether there's any other workaround if you're dead set on declaring these inside the object literal syntax: no.
Problem 2
Looks good enough to me, though I'd try to avoid using the object's name so deep into its definition.
Consider using prototyping instead.
Code Snippets
ns = {};
ns.a = function (x, y) { return x+y; };
ns.b = ns.a;Context
StackExchange Code Review Q#6740, answer score: 4
Revisions (0)
No revisions yet.