下面的代码会引发错误,指出 this.getDateString()
不是一个函数。
const Model = function () {
let dateParam = this.getDateString();
this.getDateString = function() {
let year = date.getFullYear();
let month = date.getMonth()+1;
let day = date.getDate();
return year+"-"+month+"-"+day;
}
}
我认为这是因为该函数没有被提升,所以当我在文件开头运行它时它不存在。我当然可以更改函数定义:
const Model = function () {
let dateParam = getDateString();
function getDateString() {
let year = date.getFullYear();
let month = date.getMonth()+1;
let day = date.getDate();
return year+"-"+month+"-"+day;
}
}
但我不想这样做,因为其他函数正在使用 Model
对象外部的函数。这里有什么特殊的技巧可以使用吗?也许将函数定义移到顶部?有更好的办法吗?
最佳答案
只需在 this
上添加此属性并分配该函数
const Model = function () {
let dateParam = getDateString();
this.getDateString = getDateString;
function getDateString() {
let year = date.getFullYear();
let month = date.getMonth()+1;
let day = date.getDate();
return year+"-"+month+"-"+day;
}
}
关于javascript - 如何在对象上定义函数并仍然能够运行它来设置初始对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50320418/