![](/img/trans.png)
[英]Why properties of an XMLHttpRequest object are only printable through console.log()?
[英]Why is 'this' undefined in the debugger but printable in a console.log?
當在設置斷點console.log
語句,為什么會this
可以在調試器未定義但聲明沒有問題打印? 我在范圍方面是否有所遺漏?
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);
});
}
}
}
}
使用typescript調試時,請記住,編譯器可以重命名變量。 在控制台中使用不帶重命名的源映射的原始名稱將顯示未定義,即使原始值不是。 確保在監視或控制台命令中使用已轉換的名稱。
如果引用this
與自己的類里面你的console.log語句,你在它的相關范圍使用。 根據您使用的框架,使用不同的術語來引用您的類... AngularJS使用了$scope
-Angular 2+使用this
來引用當前的類(或當前的作用域/上下文)。
在調試器中使用this
,您將在其范圍之外使用它。 它不再引用您想要的類。
Angular中的每個組件都使用this
引用自己。 這是一篇文章,將進行詳細說明: https : //angular-2-training-book.rangle.io/handout/features/refresher_on_this.html
如果我們將其簡化為基本的javascript並將您的類視為一個函數,那么一個很好的例子就是:
function example(){
var anything = 10;
console.log(anything); //output: 10
}
console.log(anything); //undefined! we're out of scope :)
因此,從這個角度來看, this
並不是什么神奇的事情。 它只是由Angular提供給我們的,目的是使我們對組件內部其他內容的引用更加容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.