Martyn Ball
Martyn Ball

Reputation: 4895

Referencing self from anonymous function

Not sure how to word this, I basically want to extend my class properties so that users can override them. However I'd prefer the anonymous function which extends the properties to just self-execute.

var extend = function(target, sources) {
      if (!sources.length) return target;
      const source = sources.shift();

      if (isObject(target) && isObject(source)) {
        for (const key in source) {
          if (isObject(source[key])) {
            if (!target[key]) Object.assign(target, { [key]: {} });
            extend(target[key], source[key]); // <-- Line 9
          } else {
            Object.assign(target, { [key]: source[key] });
          }
        }
      }
      return extend(target, sources);
    }.call(this, this, [ defaults, options ]);

This appears to work up until line 9 (see comment above in code). It can't seem to reference itself. However this seems to work fine if this is a named function rather than anonymous.

How can I get this to work?

Upvotes: 0

Views: 66

Answers (1)

pethel
pethel

Reputation: 5537

Why you need it to be anonymous? Debugging gets worse. You can still use a function expression.

const myfunc = function nameFunctionExpression(i) {
  if(i === 10) {
    return i;
  }
  nameFunctionExpression(i + 1);
};

myfunc(0);

I am not sure about what you are trying to accomplish. Provide a way to override properties? Maybe post an usage example?

function extend(obj, rest) {
  return Object.assign(obj, rest);
}

const obj = { a: 1, nested: { c: 3 } };

// { a: 2, nested: { c: 4 }, b: 3 }
console.log(extend(obj, { a: 2, b: 3, nested: { c: 4 } }));

Upvotes: 1

Related Questions