英文:
How do I debug a Javascript class that is part of a React application?
问题
当我开发一个React组件时,我使用console.log()
语句进行调试。当组件被渲染时,console.log()
语句会被打印到控制台,这是我目前用于调试的全部内容。
但是,我如何调试JavaScript类呢?我想在JavaScript类中也使用我的console.log()
语句。但是该类本身不会被渲染到DOM中,所以位于该类中的console.log()
语句也不会被打印到控制台。
一个简单的JavaScript类。
class MyClass {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, ${this.name}!`);
}
}
英文:
When I develop a React Component, I use the console.log()
statement for debugging. When the component is rendered, the console.log()
statement is printed into the console and that is all that I presently use for my debugging.
But how do I debug a javascript class? I would like to use my console.log()
statements also in a Javascript class. But how can I do that? The problem is that the class itself does not get rendered into the DOM, so the console.log()
statements [placed in the class] are also not printed into the console.
A simple Javascript class.
class MyClass {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, ${this.name}!`);
}
}
答案1
得分: 1
只有在从实例调用函数sayHello
时,才会执行console.log()
,然后您可以在控制台中看到它。现在您没有在任何地方调用sayHello
。
class MyClass {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, ${this.name}!`);
}
}
const obj = new MyClass('Jimmy Dean');
obj.sayHello()
英文:
Only when you call the function sayHello
from an instance will the console.log()
execute and you can see it inside the console. Right now you are not calling sayHello
anywhere.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
class MyClass {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, ${this.name}!`);
}
}
const obj = new MyClass('Jimmy Dean');
obj.sayHello()
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论