我正在尝试使用getter和setter调整最初使用类构造函数设置的数据。吸气剂似乎有效:
function parseTime(timeString)
{
if (timeString == '') return null;
var d = new Date();
var time = timeString.match(/(\d+)(:(\d\d))?\s*(p?)/i);
hrs = parseInt(time[1],10) + ( ( parseInt(time[1],10) < 12 && time[4] ) ? 12 : 0);
return amPm = hrs > 11 ? 'pm' : 'am';
}
time = '14:00:00';
var date = parseTime(time);
print(date);
但这会收到错误
zakeyumidu.js:27 Uncaught TypeError:this.theData不是函数
at myClass.create
创建非class myClass {
constructor(sth) {
this.data = {
sth,
timestamp: new Date()
}
}
create(createData) {
const newData = Object.assign({}, this.theData, {
/* this getter seems to work ^^^^^^^^^^^^ */
createData
})
console.log(newData) // looks good
// set'ter new data
this.theData(newData)
return this
}
get theData() {
return this.data
}
set theData(newData) {
console.log('setting')
this.data = newData;
}
}
const Instance = new myClass('construct data')
.create({createData: 'some data'})
方法似乎可以正常工作
setter
但我认为setTheData(newData) {
this.data = newData // yep, that works
}
/ getters
是首选。
答案 0 :(得分:2)
而不是this.theData(newData)
,您应该写this.theData = newData
class myClass {
constructor(sth) {
this.data = {
sth,
timestamp: new Date()
}
}
create(createData) {
const newData = Object.assign({}, this.theData, {
/* this getter seems to work ^^^^^^^^^^^^ */
createData
})
console.log(newData) // looks good
// set'ter new data
this.theData = newData;
return this
}
get theData() {
return this.data
}
set theData(newData) {
console.log('setting')
this.data = newData;
}
}
const Instance = new myClass('construct data')
.create({createData: 'some data'})
答案 1 :(得分:1)
this.theData(newData)
将访问theData
的 getter 。由于.data
在行执行时(或永远)不是函数,所以这就是你得到错误的原因。
要解决此问题,您应该实际使用setter:
this.theData = newData;