简体   繁体   English

Javascript文字对象内的私有var

[英]Private var inside Javascript literal object

How can I declare a private var inside a literal object? 如何在文字对象中声明私有变量? Becasuse I've this code: 因为我有这段代码:

var foo = {

    self: null,

    init: function() {
        self = this;
        self.doStuff();
    },

    doStuff: function() {
        //stuff here
    }

}

This works perfectly, but if I have some objects, the var "self" it will override.. apparently it's a global var.. and I cannot use the restricted word "var" inside this object.. 这可以完美地工作,但是如果我有一些对象,则它会覆盖var“自我” ..显然它是全局var ..并且我不能在该对象内使用受限词“ var”。

How can I solve this, or make an NameSpace for each object? 我该如何解决这个问题,或者为每个对象创建一个名称空间?

Thanks! 谢谢!

You can create a function scope to hide the variable: 您可以创建函数作用域以隐藏变量:

var foo = (function() {
  var self = null
  return {
    init: ...,
    doStuff: ...
  };
})();

Though it is not clear what self is supposed to do here, and how foo is used. 尽管尚不清楚self应该在这里做什么以及如何使用foo

You have to use this : 您必须使用this

init: function() {
  this.self = this;
  this.self.doStuff();
},

edit However, it's still a property of the "foo" object, and it's not super-clear where you're getting instances of "foo" from. 编辑但是,它仍然是“ foo”对象的属性,并且不清楚从何处获取“ foo”的实例。 In other words, the way your code is written, there's only one object. 换句话说,编写代码的方式只有一个对象。

Alternatively, you could create your object with a closure: 或者,您可以使用闭包创建对象:

var foo = function() {
    var self = null;

    return {
      init: function() {
        self = this;
        self.doStuff();
      },

      doStuff: function() {
        //stuff here
      }
    };
}();

You are not even using the property that you have created. 您甚至都没有使用创建的属性。 Instead you create another global variable with the same name. 相反,您将创建另一个具有相同名称的全局变量。 Use the this keyword to access properties: 使用this关键字访问属性:

var foo = {

  self: null,

  init: function() {
    this.self = this;
    this.self.doStuff();
  },

  doStuff: function() {
    //stuff here
  }

}

(Although saving this in a property is truly pointless...) (虽然保存this一个属性是真正的毫无意义的...)

If you want a local variable in the object, create a closure for it: 如果要在对象中使用局部变量,请为其创建一个闭包:

var foo = (function(){

  var self = null;

  return {

    init: function() {
      self = this;
      self.doStuff();
    },

    doStuff: function() {
      //stuff here
    }
  };

}());

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

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