简体   繁体   English

console.log 不显示由类创建的函数

[英]console.log doesn't show functions created by class

const object = {
  name: 'Andrew',
  getName() {
    return this.name
  }
}

class ObjectClass {
  constructor(name) {
    this.name = name
  }

  getName() {
    return this.name
  }
}

const object2 = new ObjectClass('Andrew')

console.log(object) // Object {name: "Andrew", getName: function getName()}
console.log(object2, 'object2') // ObjectClass {name: "Andrew", constructor: Object}

I've used codesandbox for creating this code and I get there next responses , I'm little bit confused , because I thought that object and object2 will be the same .我使用了 codeandbox 来创建此代码,然后我得到了下一个响应,我有点困惑,因为我认为objectobject2将是相同的。 {} thought that it is the same as new Object() {}以为和new Object()

When you are using a class, the class methods go to the prototype chain, which you can access with the Object.getPrototypeOf function or with the __proto__ property, although the latter is not preferable.当您使用类时,类方法转到原型链,您可以使用Object.getPrototypeOf函数或__proto__属性访问它,尽管后者不是可取的。 When you are directly making an object, the function is a property of the object itself, and so it doesn't go to the prototype chain.当你直接创建一个对象时,函数是对象本身的一个属性,所以它不会进入原型链。

Ultimately, the result of this code depends on your console.最终,此代码的结果取决于您的控制台。 For example, if you are using the Chrome console, you will be able to see everything from an object's prototype.例如,如果您使用 Chrome 控制台,您将能够查看对象原型中的所有内容。 Clearly, the console you are using doesn't have that feature.显然,您使用的控制台没有该功能。

If you need consistent results, don't console.log objects directly.如果您需要一致的结果,请不要直接使用 console.log 对象。 Instead, turn those objects into strings that you can format as needed, and then log those strings.相反,将这些对象转换为您可以根据需要格式化的字符串,然后记录这些字符串。

There are characteristics that distinguish simple objects and classes in Javascript, most notably - from your example - is the accessor method you found missing.有一些特征可以区分 Javascript 中的简单对象和类,最值得注意的是 - 从您的示例中 - 是您发现缺少的访问器方法。

According to the docs , "The __proto__ getter function exposes the value of the internal [[Prototype]] of an object".根据文档,“ __proto__ getter 函数公开了对象内部 [[Prototype]] 的值”。

You can begin logging internals of your class using reflection and __proto__ :您可以使用反射__proto__开始记录类的内部结构:

console.log(Object.getOwnPropertyNames(foo).concat(Object.getOwnPropertyNames(foo.__proto__)))

For more details on logging check this question: Get functions (methods) of a class有关日志记录的更多详细信息,请检查此问题: 获取类的函数(方法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM