Skip to main content
2 of 2
edited tags
Jack Bashford
  • 44.3k
  • 11
  • 56
  • 84

How can I provide protection and confidentiality?

I want to restrict access to certain things in the JavaScript language from the outside. I've done some research on this, but I haven't been able to get anything I want. I know the underscore doesn't provide complete protection. When I try to reach from outside, I can easily reach. I'm going to write a sample code.

  function Car(){
    this._mileage = 0;
  }

  Car.prototype.drive = function(miles){
    if(typeof miles == 'number' && miles > 0){
      this._mileage += miles;
    }else{
      throw new Error("Sadece pozitif sayılar girin");
    }
  };

  Car.prototype.readMileage = function(){
    return this._mileage;
  }
  
  var hondo = new Car();
    console.log('old: '+hondo._mileage);
  hondo._mileage = 100;
  console.log('new: '+hondo._mileage);

As you can see: Although I used underscores, I could easily access from outside the classroom.

Another method

I found a method in my research. But I don't quite understand that either.

  var Car = (function(){
    var _ = PrivateParts.createKey(); // createKey = ?

    function Car(mileage){
      _(this).mileage = mileage;
    }
    Car.prototype.drive = function(miles){
      if( typeof miles == 'number' && miles > 0){
        _(this).mileage += miles;
      }else{
        throw new Error('drive only accepts positive numbers');
      }
    }
    Car.prototype.readMileage = function(){
      return _(this).mileage;
    }
    return Car;
  }());

user11264432