is it possible to call the setter function outside the constructor class?
ie i have the following class
class example {
constructor() {
this._partner = 0;
}
get partner() {
return this._partner;
}
set partner(id) {
this._partner = id;
}
}
when i call
friends = new example();
freinds.partner(75);
i see the follwing error:
Uncaught TypeError: example.partner is not a function
To invoke a setter/getter, it has to look from the outside as if you're directly setting or retrieving a property on the object (not calling a function):
class example { constructor() { this._partner = 0; } get partner() { console.log('getter running'); return this._partner; } set partner(id) { console.log('setter running'); this._partner = id; } } friends = new example(); console.log('about to assign to .partner'); friends.partner = 75; console.log('about to retrieve .partner'); console.log(friends.partner);
Note that the parameter that the setter sees is the value that looks like got "assigned" to the property outside.
这些setter和getter使您可以直接使用属性(无需使用括号)
friends.partner = 75;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.