function Point () {
this.xPos = 0;
this.yPos = 0;
}
Object.__defineGetter__.call(Point.prototype, "getPoint", function(){
return "X: " + this.xPos + " Y: " + this.yPos;
});
Object.__defineSetter__.call(Point.prototype, "setPoint", function(point){
var parts = point.toString().split(', ');
parts[0] = this.xPos;
parts[1] = this.yPos;
});
var newPoint = new Point();
newPoint.setPoint("44.5, 60.6");
console.log(newPoint.getPoint);
Run Code Online (Sandbox Code Playgroud)
它返回一个错误: newPoint.setPoint 不是函数。不明白为什么你能帮助我?尝试处理 setter 和 getter。
您遇到的主要问题是通过使用赋值运算符来调用设置器=。
newPoint.setPoint = "44.5, 60.6";
Run Code Online (Sandbox Code Playgroud)
newPoint.setPoint = "44.5, 60.6";
Run Code Online (Sandbox Code Playgroud)
Object.defineProperty您还可以使用或的标准 api,Object.defineProperties对于查看代码的其他人来说,这将更容易遵循。
Object.defineProperty(Point.prototype, "getPoint", {
get: function(){
return "X: " + this.xPos + " Y: " + this.yPos;
},
set: function() {
// stuff
}
});
Run Code Online (Sandbox Code Playgroud)
或使用 ES6
class Point {
constructor() {
this.xPos = 0
this.yPos = 0
}
get getPoint() {
// stuff
}
set setPoint() {
// stuff
}
}
Run Code Online (Sandbox Code Playgroud)