通过程序从构造函数中检索属性名称

programatically retrieve property names from constructor

本文关键字:检索 属性 构造函数 过程 程序      更新时间:2023-09-26

我正在努力学习javascript,并试图为项目找出本地存储。但首先我认为我需要通过编程从我的团队构造函数中构建密钥。

 var Team = function(team, manager, cell, add1, add2, city, st, zip, sponsor) {
  this.team = team;
  this.manager = manager;
  this.cell = cell;
  this.add1 = add1;
  this.add2 = add2;
  this.city = city;
  this.st = st;
  this.zip = zip;
  this.sponsor = sponsor;
  };

这是我构建的一个表单,现在我想构建本地存储。这是我失败的尝试:

 function saveTeam() {
 for (var i = 0; i < Team.length; i++) {
 localStorage["league." + i "." + javascriptNameOfProperty ] = $('#'+ javascriptNameOfPropertyName + ').val() };

或者类似的东西。我尝试过"property"、"key"和其他我尝试过的不适用于property的javascriptName。当然,一旦我弄清楚了,我就必须弄清楚本地存储。

在这种情况下,您可以使用对象文字而不是构造函数(我看不出您发布的代码中有任何构造函数的原因,您应该使用new实例化对象,但事实并非如此)。考虑使用这个(假设您传递给Team的所有变量都已定义):

var team = {
    team : team,
    manager : manager,
    cell : cell,
    add1 : add1,
    add2 : add2,
    city : city,
    st : st,
    zip : zip,
    sponsor : sponsor
}

这可以用以下代码迭代:

for(var key in team) {
    localStorage["league." + key] = team[key];
}

我认为这并不是你的原始代码想要做的事情,但不清楚你是否有多个团队,他们是如何创建的,以及他们是如何使用的。我希望这会有所帮助。

团队是一个函数,而不是数组。

我假设你确实有一系列的团队。

您需要使用for in循环:

var teams = [ ... ];
for (var i = 0; i < teams.length; i++) {
    for (var key in team) {
        localStorage["league." + i + "." + key] = $('#' + key).val()
    }
}

要从其他人身上构建一点,也可以这样做。

var Team = function(team, manager, cell, add1, add2, city, st, zip, sponsor) {
  this.team = team;
  this.manager = manager;
  this.cell = cell;
  this.add1 = add1;
  this.add2 = add2;
  this.city = city;
  this.st = st;
  this.zip = zip;
  this.sponsor = sponsor;
};
Team.prototype.save = function () { 
  for ( var prop in this )
  { 
    if (this.hasOwnProperty(prop))
      console.log('%s => %s', prop, this[prop]);
      // your localStorage saving logic goes here
  }
};
var t = new Team('vteam','vmanager','vcell','vadd1','vadd2','vcity','vst','vzip','vsponors');
t.save();

这将只保存团队对象的属性(团队函数This.prop.

中定义的任何属性)