HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Functions in object literals

Submitted by: @import:stackexchange-codereview··
0
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?

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.

Solution

Problem 1

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.