user3376708
user3376708

Reputation:

Can you use setters and getters in Javascript code?

Below in my code example there is an example of a getter and setter is this the proper way of using them in Javascript?

Question: Is this how to use a getter and setter in Javascript?

Code:

<body>
<p>Object</p>

<script>
function Car( model, year, miles ) {
  this.model;
  this.year = year;
  this.miles = miles;

  this.setmodel = function (m) {
    if (do some checks here) {
       this.model = m;
    }
  };

  this.getmodel = function () {
    return model;
  };  

  this.toString = function () {
    return this.model + " has done " + this.miles + " miles";
  };
}

Car.prototype.toAnotherString = function () {
   return this.model + " has done " + this.miles + " miles";
};

var civic  = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );

console.log( civic.toString() );
console.log( mondeo.toString() );
console.log( civic.toAnotherString() );
console.log( mondeo.toAnotherString() );

alert(civic.toString());
</script>   
</body>
</html>

Upvotes: 0

Views: 68

Answers (2)

theferrit32
theferrit32

Reputation: 241

Yes you can do that, if you fix the setter to this.model = m;

and the getter to return this.model;

It isn't really necessary though. Unless you have special operations you need to perform or special validation to handle on incoming values, it just takes up extra space.

Upvotes: 0

Kevin B
Kevin B

Reputation: 95031

No, that is not correct. Your setter needs to... set the value, and your getter needs to get the value...

  this.setmodel = function (m) {
    this.model = m;
  };

  this.getmodel = function () {
    return this.model;
  }; 

Seems just a little pointless though since that property is directly available.

var civic  = new Car( "Honda Civic", 2009, 20000 );
civic.model = "Some model";

Setters and Getters are typically used for private variables that are purposely not publicly available, or for transforming data (such as your toString method)

Upvotes: 3

Related Questions