javascript - 如何在对象上定义函数并仍然能够运行它来设置初始对象属性
问题描述
下面的代码引发了一个错误,说这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;
}
}
推荐阅读
- swift - 是否可以将自定义工具添加到 PKToolPicker?
- function - 一个函数中有两个“scrollIntoView”
- sed - 使用 sed 删除目录中多个文件上的一些文本
- linux - 在哪里可以找到特定 Linux 系统库的源代码?
- php - Laravel 8:安装失败,将 ./composer.json 还原为其原始内容
- netbeans - 如果 HTML 在 PHP IF 语句中,Netbeans 语法检查错误
- c - vs 代码 esp-idf 从标准 c 库 windows 10 导入未解析
- sql - 在两个不同列或同一列中使用两个字符串进行过滤的查询
- abap - BDC SAP 中的抑制打印对话框
- python - PyInstaller 单文件抛出异常 matplotlib