如何在对象中获取函数以显示其返回值?

时间:2019-02-23 23:07:52

标签: javascript

每当我尝试将功能打印到控制台时,都会得到以下输出:

  { Subject: 'fiction',
  Author: 'John Wayne',
  PublicationDate: 1890-02-18T07:33:52.000Z,
  DaysSincePublished: [Function] } 

DaysSincePublished属性的值应该显示自书籍出版之日起至今的天数。而是显示该属性的值的类型。

function Book(Subject, Author, PublicationDate) { 

  const book = {
    Subject:Subject,
    Author:Author,
    PublicationDate:PublicationDate,
    DaysSincePublished: function() {
  const Interval = Math.round(((new Date) - this.PublicationDate) / (1000*60*60*24));
  return Interval;
    }
  }

  return book;

}

var book1 = new Book("fiction", "John Wayne", new Date("18 February 1890"));
console.log(book1);

3 个答案:

答案 0 :(得分:0)

删除“ this”,因为这是书本对象,该对象在构造前没有PublicationDate。同时运行功能以获取价值

function Book(Subject, Author, PublicationDate) { 

  const book = {
    Subject:Subject,
    Author:Author,
    PublicationDate:PublicationDate,
    DaysSincePublished: (function() {
  const Interval = Math.round(((new Date) - PublicationDate) / (1000*60*60*24));
  return Interval;
    })()
  }

  return book;

}

var book1 = new Book("fiction", "John Wayne", new Date("18 February 1890"));
console.log(book1);

答案 1 :(得分:0)

这是因为对象book在属性DaysSincePublished上具有函数,而不是值。除了进行演算并将其分配给属性外,还可以在外部进行计算并将结果值传递给属性(比起同一行中的所有操作,它更优雅,更易读)。

还要小心使用this关键字,在这种情况下,这似乎是毫无意义的。

function Book(Subject, Author, PublicationDate) { 

  function calculateDays() {
    const Interval = Math.round((new Date() - PublicationDate) / (1000*60*60*24));
    return Interval;
  }

  const book = {
    Subject:Subject,
    Author:Author,
    PublicationDate:PublicationDate,
    DaysSincePublished: calculateDays()
  }

  return book;

}

这里的区别是,您没有为属性分配功能,而是分配了该功能的评估(结果)!


一些题外话:

建议在变量名中使用camelCase,因为使用大写的名称通常用于类(例如DateMath)。我并不是说您的代码行不通,但是作为惯例,建议您使用它来避免混淆!所以例如尝试写publicationDate而不是PublicationDate

这是一个看起来更美观的代码,其功能相同:

function book(subject, author, publicationDate) { 

  function calculateDays() {
    return Math.round((new Date() - publicationDate) / (1000*60*60*24));
  }

  return {
    subject: subject,
    author: author,
    publicationDate: publicationDate,
    daysSincePublished: calculateDays()
  }
}

答案 2 :(得分:0)

种来自 Shishir Arora

的副本

function Book(Subject, Author, PublicationDate) { 
  const book = {
    Subject           : Subject,
    Author            : Author,
    PublicationDate   : PublicationDate,
    DaysSincePublished: (()=> Math.round(((new Date) - PublicationDate) / (1000*60*60*24)))()
  }
  return book;
}

var book1 = new Book("fiction", "John Wayne", new Date("18 February 1890"));
console.log(book1);