如何获取对象名称的字符串?

时间:2014-02-01 15:56:17

标签: javascript oop

我有一些对象:

var book = {}
book.title = "Big bad book"
book.size = {}
book.size.width = "1 meter"
book.size.height = "2 meter"

我想得到这样的东西

nameof(book) // book
nameof(book.size) // book.size

或者

book.objectName // book
book.size.objectName // book.size

我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用构造函数创建对象时,可以检索对象的名称:

function Book(){
  this.title = "Big bad book"
  this.size = {}
  this.size.width = "1 meter"
  this.size.height = "2 meter"
}

var book = new Book();
console.log(book.constructor.name);