【问题标题】:Setting Function as Object member with "new" notation使用“新”表示法将函数设置为对象成员
【发布时间】:2018-01-28 12:25:13
【问题描述】:

大家,我是 Javascript 的新手...我知道如何使用这种格式将函数合并到对象中...

var xyz = {
    yearOfBirth: 1963,
    calculateAge: function() {
        this.age = (new Date().getFullYear()) - this.yearOfBirth;
    }
};

***但是我需要您对其他格式的指导...

var abc = new Object();

谢谢!

【问题讨论】:

标签: javascript function object methods


【解决方案1】:

关于你的问题。当使用构造函数定义对象时,可以像这样定义属性:

var abc = new Object()
abc["yearOfBirth"]=1963

abc["calculateAge"]=function(){
    this.age=(new Date().getFullYear())-this.yearOfBirth;
}

你也可以这样做:

var abc = new Object()
abc.yearOfBirth=1963

abc.calculateAge=function(){
    this.age=(new Date().getFullYear())-this.yearOfBirth;
}

【讨论】:

  • 也没有引号,比如abc.yearOfBirth = 1963
  • 感谢您的意见@BalázsÉdes 我会在我的回答中添加这一点。
  • 感谢您的帮助和快速响应。
  • 我曾经和你一样@CarlosMalovini,我明白。
猜你喜欢
  • 2012-04-29
  • 2013-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 1970-01-01
相关资源
最近更新 更多