[英]Why is 'this' undefined in the debugger but printable in a console.log?
When setting a breakpoint on the console.log
statement, why would this
be undefined in the debugger but the statement print with no issues? 当在设置断点console.log
语句,为什么会this
可以在调试器未定义但声明没有问题打印? Am I missing something in regards to scope here? 我在范围方面是否有所遗漏?
export class OptionsSidebarComponent {
...
public filters: Object = new Object();
...
public generateFilters() {
for (let property in this.terms) {
if (this.terms.hasOwnProperty(property) && this.terms[property] !== null) {
if (!this.filters.hasOwnProperty(this.productGroup.id)){
this.filters[this.productGroup.id] = new Filters();
}
this.terms[property].forEach((term) => {
console.log(this.filters);
});
}
}
}
}
With typescript While debugging, keep in mind that transpilers can rename variables. 使用typescript调试时,请记住,编译器可以重命名变量。 Using the original name in the console without sourcemaps that include renaming will show you undefined even if the original value isn't. 在控制台中使用不带重命名的源映射的原始名称将显示未定义,即使原始值不是。 Make sure you use the transpiled name in watches or console commands. 确保在监视或控制台命令中使用已转换的名称。
When you're referencing this
with your console.log statement inside its own class, you're using it in its relevant scope. 如果引用this
与自己的类里面你的console.log语句,你在它的相关范围使用。 Depending on the framework you are using, different terms are used to reference your class... AngularJS used $scope
- Angular 2+ uses this
to reference the current class (or current scope/context). 根据您使用的框架,使用不同的术语来引用您的类... AngularJS使用了$scope
-Angular 2+使用this
来引用当前的类(或当前的作用域/上下文)。
When you use this
in your debugger you're using it outside of its scope. 在调试器中使用this
,您将在其范围之外使用它。 It no longer references the class you intend it to. 它不再引用您想要的类。
Each one of your components in Angular uses this
to reference itself. Angular中的每个组件都使用this
引用自己。 Here's an article to explain in further detail: https://angular-2-training-book.rangle.io/handout/features/refresher_on_this.html 这是一篇文章,将进行详细说明: https : //angular-2-training-book.rangle.io/handout/features/refresher_on_this.html
If we simplify it to basic javascript and look at your class as just a function a good example would be this: 如果我们将其简化为基本的javascript并将您的类视为一个函数,那么一个很好的例子就是:
function example(){
var anything = 10;
console.log(anything); //output: 10
}
console.log(anything); //undefined! we're out of scope :)
So looking at it from this perspective, this
is nothing magical. 因此,从这个角度来看, this
并不是什么神奇的事情。 It's just provided to us by Angular to make our references to other things inside our components easier. 它只是由Angular提供给我们的,目的是使我们对组件内部其他内容的引用更加容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.