在我的代码示例下面,有一个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>
最佳答案
不,那是不正确的。您的设置者需要...设置值,而您的获取者需要获取值...
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";
Setter和Getters通常用于故意不公开使用的私有变量,或用于转换数据(例如您的
toString
方法)