Public and private properties inside constructors

I found similar questions, but none of them answered this explicitly, so I hope someone can help me figure it out.

Regarding design functions, I'm trying to figure out if variables and functions are public or private by default.

For example, I have this sample constructor with these properties:

function Obj() {
  this.type = 'object';
  this.questions = 27;
  this.print = function() {
    console.log('hello world');
  }
}

I can name these properties as such:

var box = new Obj();
box.type; // 'object'
box.print(); // 'hello world'

It seems to me that both functions and variables are public by default. It is right? Or, if the functions inside the constructors are private ... can they only accept private variables as parameters?

Thanks.

+4
1

Javascript (, this.property = xxx) - .

Object.defineProperty(), , .

Javascript "private". , , .

, :

function Obj() {
  this.type = 'object';
  this.questions = 27;
  this.print = function() {
    console.log('hello world');
  }
}

type, questions print .


"private" - :

function Obj() {
  var self = this;

  // this is private - can only be called from within code defined in the constructor
  function doSomethingPrivate(x) {
      console.log(self.type);
  }

  this.type = 'object';
  this.questions = 27;
  this.print = function(x) {
    doSomethingPrivate(x);
  }
}

: http://javascript.crockford.com/private.html.

+4

Source: https://habr.com/ru/post/1617358/


All Articles