-1

I'm building a library that is a loading screen which allows me to call Loader.Show(), Loader.Hide() or Loader.Step() from various different documents.

I've built the library, however I do not fully understand the various ways to declare objects. Whats the difference in the following two models, and which is better?

//Example 1
var Robot = (function () {
	var metal = "Steel";
  
  return {
    killAllHumans: function() {
        alert(metal);
    }
  }
})();
Robot.killAllHumans();

//Example 2
var NonRobot = {
  runState: "Normal",
  run: function() {
  	alert(this.runState);
  }
}
NonRobot.run();

I understand that both example 1 & create objects. I also understand that in Example 1, metal is a private variable. I do not know how to create a private variable in example 2. Is the only difference the scope?

1
  • Without a constructor function you can't create a private scoped variable. Commented Dec 31, 2016 at 2:41

2 Answers 2

2

This method creates a private context where you could add your own variable and do some intermediate evalations or even create private variables, such as metal

var Robot = (function () {
    var metal = "Steel";

  return {
    killAllHumans: function() {
        alert(metal);
    }
  }
})();

On the other hand, this version creates is an object literal:

var NonRobot = {
  runState: "Normal",
  run: function() {
    alert(this.runState);
  }
}
NonRobot.run();

runState is not a private property of NonRobot and it can be manipulated by outside forces.

Sign up to request clarification or add additional context in comments.

Comments

0

In the first instance you are using an Immediately Invoked Function Expression as a constructor.

In the second, you are creating an object using an object literal.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.