首页 > 解决方案 > 如何在对象上定义函数并仍然能够运行它来设置初始对象属性

问题描述

下面的代码引发了一个错误,说这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对象外部的函数。有什么特别的技巧可以在这里使用吗?也许将函数定义移到顶部?有没有更好的办法?

标签: javascript

解决方案


只需添加此属性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;
  }
}


推荐阅读