asdasdasdasdqwe
asdasdasdasdqwe

Reputation: 331

Why doesn't this block of code work?

I've mocked up some code here

var common = common || {};

(function(NAMESPACE) {

  NAMESPACE = {
    isIE: function() {
        return true;
    }
  };

  main();

})(common);

function main() {
    console.log(common.isIE());
  return 'Hello, World!';
}

I would like to understand a couple of things,

1) Why isn't this working, I guess it has something to do with how scoping is "decided" and IIFE, but not entirely sure.

2) How to make this code work?

Upvotes: 0

Views: 72

Answers (2)

Charlie
Charlie

Reputation: 23798

When you are passing an object as an argument in JS, you should remember that you are passing "by-value" the reference of it.

Creating a new object in literal notation and assigning it to the argument like this,

NAMESPACE = {
    isIE: function() {
        return true;
    }
  };

can only point the argument to the new object - not to the object of the reference you passed the argument by.

If you had said,

NAMESPACE.isIE = function() {}

it would work.

Upvotes: 0

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

common which passed as argument named NAMESPACE needs to be extended instead of assigning new value.

So Object.assign can help here.

var common = common|| {};

(function(NAMESPACE) {

  Object.assign(NAMESPACE,{
    isIE: function() {
        return true;
    }
  });

  main();

})(common);

function main() {
    console.log(common.isIE());
  return 'Hello, World!';
}

Upvotes: 5

Related Questions