下面在我的代码示例中有一个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>
答案 0 :(得分:3)
不,这不正确。你的setter需要...设置值,你的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";
Setters和Getters通常用于故意不公开的私有变量,或用于转换数据(例如toString
方法)
答案 1 :(得分:0)
是的,如果您将设置器修改为this.model = m;
和吸气者到return this.model;
虽然这不是必要的。除非你有特殊操作需要执行或特殊验证来处理传入的值,否则它只占用额外的空间。