在 Angular 中的 window 对象中存储一个值有什么好处?

What is the advantage of storing a value in window object in Angular?

我正在经历 this code, and on this line 我看到

(window).user = user;

我想知道将用户对象设置为 window 对象中的值的重要性是什么?我知道这可能是为了将来更容易访问,但是用户对象也存储在一个可观察对象中,get user() 方法从可观察对象中检索它:

getUser(): Observable<any> {
    return this.$userSource.asObservable();
}

同样来自this answer 我的理解是:

In JavaScript, any global variable is actually a property of the window object. Using one is equivalent to (and interchangeable with) using the other.

所以我的问题是:

  1. 将用户对象设置为 window 对象中的值有何重要性?
  2. 如果我们去掉在 window 对象中存储代码的行,代码还能正常运行吗?
  3. typescript类中的全局变量和window对象的属性一样吗?例如: this value 也是 window 对象的 属性 吗?

window 对象是全局的。

这意味着如果你写

window.user = null

您已经删除了图书馆先前设置的值。

将变量存储到 window 对象中通常被认为是一种不好的做法。

为您解答:

  1. 一点都不重要,甚至气馁
  2. 你得去图书馆看看
  3. 不,他们不是:没有 "global class variable"。它要么是全局变量,要么是 class 成员。但是全局变量也可以在 Typescript 中创建。

在全局上使用变量几乎没有问题。

  1. window 是全局的。

这是一个危险的例子。

window.item = {
    name: 'Something great'
};
function selectItem() { //wrong line
    item.name = 'selected';
}
selectItem(event.target);

如您所见,开发人员忘记为函数 selectItem 添加参数 item。期望更改被点击项的名称,但全局项将被更改。

  1. this = window,如果不使用strict modethis等于window

让我们继续使用相同的示例,但这次我们将使用上下文。

function selectItem() {
     this.name = 'selected'
}
const item = {
     name: 'An item'
}
selectItem.call(item); //Assume that item is somehow undefined or null.

同样的结果,window.name将被更改。

  1. global是为了全局,封装起来。

我可以轻松访问 window 及其变量。我也可以定义与您相同的变量。或者我可能会访问您的变量,这将是一个安全问题。

  1. 测试

您无法轻易地测试具有全局变量的东西。因为它没有封装到你的范围内。

  1. 在全局范围内,没有垃圾回收。我想危险已经很明显了。

回答您的问题:

  1. 阅读以上内容
  2. 阅读以上内容
  3. 那一行有一个public属性。它不是全球性的。它未在 window 上定义。它将是实例的 属性。