简体   繁体   English

JavaScript对象声明

[英]Javascript object declaration

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. 我正在构建一个库,该库是一个加载屏幕,允许我从各种不同的文档中调用Loader.Show(),Loader.Hide()或Loader.Step()。

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. 我了解示例1和创建对象。 I also understand that in Example 1, metal is a private variable. 我还知道在示例1中,金属是私有变量。 I do not know how to create a private variable in example 2. Is the only difference the scope? 我不知道如何在示例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 此方法创建了一个私有上下文,您可以在其中添加自己的变量并进行一些中间评估,甚至创建私有变量,例如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. runState是不是一个私有财产NonRobot ,它可以通过外部力量来操纵。

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 . 在第二篇中,您将使用对象常量创建对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM