本文介绍了如何在构造函数中设置javascript私有变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 Foo 的javascript函数/类,它有一个名为 bar 的属性。我希望在实例化类时提供 bar 的值,例如:

Say I have a javascript function/class called Foo and it has a property called bar. I want the value of bar to be supplied when the class is instantiated, e.g:

var myFoo = new Foo(5);

myFoo.bar 设置为5。

如果我使 bar 一个公共变量,那么这是有效的,例如:

If I make bar a public variable, then this works, e.g:

function Foo(bar)
{
    this.bar = bar;
}

但如果我想将其设为私有,例如:

But if I want to make it private, e.g:

function Foo(bar)
{
   var bar;
}

然后我如何设置私有变量的值 bar 使其可用于 foo的所有内部函数

Then how would I set the value of the private variable bar such that its available to all internal functions of foo?

推荐答案

你必须在构造函数中放置需要访问私有变量的所有函数:

You have to put all functions that need to access the private variable inside the constructor:

function Foo(bar)
{
  //bar is inside a closure now, only these functions can access it
  this.setBar = function() {bar = 5;}
  this.getBar = function() {return bar;}
  //Other functions
}

var myFoo = new Foo(5);
myFoo.bar;      //Undefined, cannot access variable closure
myFoo.getBar(); //Works, returns 5

这篇关于如何在构造函数中设置javascript私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:00
查看更多