gpt4 book ai didi

javascript - Setter 和 Getter 错误

转载 作者:行者123 更新时间:2023-11-30 09:43:27 25 4
gpt4 key购买 nike

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);

它返回一个错误:newPoint.setPoint 不是一个函数。不明白为什么你能帮助我?尝试处理 setter 和 getter。

最佳答案

您遇到的主要问题是通过使用赋值运算符 = 来调用 setter。

newPoint.setPoint = "44.5, 60.6";

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(', ');
// the assignment to this.xPos and this.yPos was the wrong way around
this.xPos = parts[0];
this.yPos = parts[1];
});

var newPoint = new Point();

// a setter is called by assigning a value to it
newPoint.setPoint = "44.5, 60.6";

console.log(newPoint.getPoint);

您还可以使用 Object.definePropertyObject.defineProperties 的标准 API,这对于查看代码的其他人来说更容易理解。

Object.defineProperty(Point.prototype, "getPoint", {
get: function(){
return "X: " + this.xPos + " Y: " + this.yPos;
},
set: function() {
// stuff
}
});

或者使用 ES6

class Point {
constructor() {
this.xPos = 0
this.yPos = 0
}
get getPoint() {
// stuff
}
set setPoint() {
// stuff
}
}

关于javascript - Setter 和 Getter 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40059535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com