你能在Javascript代码中使用setters和getters吗?

Can you use setters and getters in Javascript code?

本文关键字:setters getters Javascript 代码      更新时间:2023-09-26

在我的代码示例中,下面有一个getter和setter的示例,这是在Javascript中使用它们的正确方法吗?

问题:这是如何在 JavaScript 中使用 getter 和 setter 吗?

法典:

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

不,这是不正确的。您的二传手需要...设置值,您的 getter 需要获取值...

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

似乎有点毫无意义,因为该属性可以直接使用。

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

设置器和 Getter 通常用于故意不公开可用的私有变量,或用于转换数据(例如 toString 方法)

是的,你可以这样做,如果你将二传手固定为this.model = m;

和吸气剂return this.model;

不过,这并没有必要。除非您需要执行特殊操作或特殊验证来处理传入值,否则它只会占用额外的空间。