我有一个dog类,其中包含私有成员,这些私有成员具有使用闭包访问这些成员的公共方法。
class Dog {
constructor(name, age, avail) {
var _name, _age, _availability;
_name = name;
_age = age;
_availability = avail;
this.getName = function () {
return _name;
}
this.getAge = function () {
return _age;
}
this.getAvailability = function () {
return _availability;
}
}
Dogs[0] = new Dog("Macy","6 Years", true);
我希望能够更改能够更改_availability成员。 我尝试添加:
this.setAvailbility = function (param) {
if (param == "false") {
_availability = false;
} else if (param == "true") {
_availability = true;
}
但这没用。我该怎么做呢?
class Dog {
constructor(name, age, avail) {
var _name, _age, _availability;
_name = name;
_age = age;
_availability = avail;
this.getName = function() {
return _name;
}
this.getAge = function() {
return _age;
}
this.getAvailability = function() {
return _availability;
}
this.setAvailbility = function(param) {
if (param == "false") {
_availability = false;
} else if (param == "true") {
_availability = true;
}
}
}
}
var dog = new Dog("Macy", "6 Years", true);
dog.setAvailbility("false");
console.log(dog.getAvailability())
答案 0 :(得分:0)
尝试像这样创建一个setter方法setAvailability(avail)
:
class Dog {
_name;
_age;
_availability;
constructor(name, age, avail) {
this._name = name;
this._age = age;
this._availability = avail;
}
getName() {
return this._name;
}
getAge() {
return this._age;
}
getAvailability() {
return this._availability;
}
setAvailability(avail) {
this._availability = avail;
}
}
const dog = new Dog("Macy", "6 Years", true);
console.log('Name:', dog.getName());
console.log('Age:', dog.getAge());
console.log('Availability:', dog.getAvailability());
dog.setAvailability(false);
console.log('Updated availability:', dog.getAvailability());