Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
808 views
in Technique[技术] by (71.8m points)

oop - How to set javascript private variables in constructor?

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);

would set myFoo.bar to 5.

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;
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One of the best tutorials on private and protected access in javascript is here: http://javascript.crockford.com/private.html.

function Foo(a) {
    var bar = a;                              // private instance data

    this.getBar = function() {return(bar);}   // methods with access to private variable
    this.setBar = function(a) {bar = a;}
}

var x = new Foo(3);
var y = x.getBar();   // 3
x.setBar(12);
var z = x.bar;        // not allowed (x has no public property named "bar")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...