【问题标题】:What is the difference between properties of an constructor function that are visible with `console.log` vs those that are visible with `console.dir`?使用 `console.log` 可见的构造函数的属性与使用 `console.dir` 可见的构造函数的属性有什么区别?
【发布时间】:2018-06-01 13:55:39
【问题描述】:

在控制台中,当我定义一个构造函数,然后在事后向它添加一个属性时,运行console.log(myConstructor) 不会泄露该属性。但是,当我运行console.dir(myConstructor) 时,我现在可以看到我添加的属性以及许多其他属性。我可以使用console.log 看到的属性与我看不到的属性有什么区别?是否有可以用来区分这两种属性的特定术语或词汇?

function myConstructor(){
  this.sayHi = function(){
    console.log("hey")
  }
}

myConstructor.boop = "thing"

console.log(myConstructor)

=> ƒ myConstructor(){
       this.sayHi = function(){
         console.log("hey")
       }
     }

console.dir(myConstructor)

=> ƒ myConstructor()
       boop : "thing"
       arguments:null
       caller:null
       length:0
       name:"myConstructor"
       prototype:{constructor: ƒ}
       __proto__:ƒ ()
       [[FunctionLocation]]:VM123:1
       [[Scopes]]:Scopes[1]

【问题讨论】:

  • 这取决于浏览器/js环境如何实现console。所有浏览器的日志记录行为或多或少不同。即使在浏览器版本之间,也可能存在差异。
  • 您是否检查过 .log.dir 上的 MDN 文档,看看是否回答了您的问题?
  • @Nope 是的,我有。我不是在问这两种方法之间的区别。我在问 console.log 显示的属性与不显示的属性有什么区别。 MDN 文档说console.log prints the element in an HTML-like tree while console.dir prints the element in a JSON-like tree. 这没有回答我的问题。

标签: javascript google-chrome-console browser-console


【解决方案1】:

请查找对 console.dir 的引用以了解发生这种情况的原因: https://developer.mozilla.org/en-US/docs/Web/API/Console/dir

console.log 记录你扔在那里的任何东西(在你的情况下它会记录函数)并且 dir 记录对象的属性;来自文档:

换句话说,console.dir 是在控制台中查看指定 javascipt 对象的所有属性的方式,开发人员可以通过它轻松获取对象的属性。

【讨论】:

  • 我认为我遇到的问题是我一直听说functions are objects in Javascript。那么为什么我能够打印出 1)使用 console.log 的函数和 2)使用 console.dir 的对象?这两件事有什么区别,它们的关系是什么?它们只是同一功能的不同表示吗?
  • 我认为console.log 只是执行该功能的“某种” toString。 console.dir 显示函数的属性,在控制台中查看这两个调用的区别: console.dir(function() {return'1'}) console.log(function() {return'1'})
猜你喜欢
  • 1970-01-01
  • 2016-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
  • 1970-01-01
  • 2012-06-15
相关资源
最近更新 更多