Here, through the function, created an object with a variable hidden from external access and a method for working with this variable:

function Machine() { var petrol = 100; this.getPetrol = function() { return petrol; }; this.setPetrol = function(value) { petrol = value; }; } var machine = new Machine(); var p = machine.getPetrol(); machine.setPetrol(5); var newP = machine.getPetrol(); console.log(p, newP); 

Now I would like to write the same object, but not through a function, but directly through an object. Please help me do this, here is my attempt:

 var Machine = { this.petrol = 100, this.getPetrol = function() { return petrol; }, this.setPetrol = function(value) { petrol = value; } } var machine = new Machine(); machine.getPetrol(); 
  • one
  • petrol field also be protected from external access? - ThisMan
  • one
    without a function, a similar object will fail. - Grundy
  • @ThisMan is desirable. but not necessarily - cyklop77
  • one
    @ cyklop77, in this case you don’t have a block, you have an object literal, and you can’t put an arbitrary code inside like in a constructor function - Grundy

2 answers 2

In the object literal, fields are described in the following format:

 fieldName : fieldvalue 

In the first example, you add two fields to your object: getPetrol , setPetrol .

Formally, a similar object can be written as:

 var petrol = 100; var Machine = { getPetrol : function() { return petrol; }, setPetrol : function(value) { petrol = value; } } 

 var petrol = 100; var Machine = { getPetrol: function() { return petrol; }, setPetrol: function(value) { petrol = value; } } console.log(Machine.getPetrol()); 

    The first thing that comes to mind is masking the defineProperties property

    Or give access only through a unique link through es6 symbol