JavaScript中Var类型的新实例

New instance of Var type in JavaScript

本文关键字:实例 新实例 Var 类型 JavaScript      更新时间:2024-05-21

如何在JavaScript中创建变量的var类型的新实例?

例如

var UserControl = { Id: '', Location: { Left: 0, Top: 0, Width: 0, Height: 0 }, Contents: '', Name: '' };

我想把这个UserControl存储在JavaScript数组中。如下图所示。

UserControl.Id = '1';
UserControl.Location.Left = offset.left;
UserControl.Location.Top = offset.top;
UserControl.Location.Width = offset.left + area.width();
UserControl.Location.Height = offset.top + area.height();
UserControlCollection.push(UserControl);

但是UserControl会覆盖以前的条目,因为UserControl不会创建新实例。

有这个指针吗?

您可以尝试使用函数作为构造函数,比如这个

function UserControl() {
  this.Id = '';
  this.Location = {
    Left: 0, Top: 0, Width: 0, Height: 0
  };
  this.Contents = '';
  this.Name = '';
}

示例