JavaScript:为什么要获取上次插入的值

JavaScript: Why getting last inserted values?

本文关键字:插入 获取 为什么 JavaScript      更新时间:2023-09-26

我正在熟悉JavaScript和this关键字的原型世界。我是网络世界的新手。今天当我开始使用原型时,我看到了一些奇怪的行为,但我无法理解为什么会发生这种情况。我创建了一个构造函数Group如下所示:

// Code goes here
function Group(config) {
  this.config = config;
  this.getId = function() {
    return this.config.id;
  };
  this.setId = function(id) {
    this.config.id = id;
  };
}

我在一个MyGroup构造函数中使用它,如下所示:

function MyGroup(config) {
  var myAttrs = ['id', 'name'];
  this.g = new Group(config);
  addGetterSetter(MyGroup, this.g, myAttrs)
}

addGetterSetter是我编写的函数,用于将 getter 和 setter 动态添加到 MyGroup 的属性中。

var GET = 'get',
  SET = 'set';
function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
function addGetterSetter(constructor, target, attrs) {
  function addGetter(constructor, target, attr) {
    var method = GET + capitalize(attr);
    constructor.prototype[method] = function() {
      return target[method]();
    };
  }
  function addSetter(constructor, target, attr) {
    var method = SET + capitalize(attr);
    constructor.prototype[method] = function(value) {
      return target[method](value);
    };
  }
  for (var index = 0; index < attrs.length; index++) {
    addGetter(constructor, target, attrs[index]);
    addSetter(constructor, target, attrs[index]);
  }
}

现在当我使用 MyGroup 时,Group这样的:

var items = [{
  id: 123,
  name: 'Abc'
}, {
  id: 131,
  name: 'Bca'
}, {
  id: 22,
  name: 'bc'
}];
var groups = [];
items.forEach(function(item) {
  var g = new MyGroup(item);
  groups.push(g);
});
groups.forEach(function(g) {
  console.log(g.getId()); //don't know why this logs 22 three times instead of all ids
});

group.forEach我不知道为什么最后一项的 id 会被记录下来。我无法理解出了什么问题。以及我将如何能够获得为其调用g.getId()的组。这是普伦克

这是因为您要向原型添加方法,并且每次使用前一个函数时都会在循环中覆盖,因此当 forEach 循环结束时,函数会保留对最后一个对象的引用。你需要的是向这个对象添加函数:

function MyGroup(config) {
  var myAttrs = ['id', 'name'];
  this.g = new Group(config);
  addGetterSetter(this, this.g, myAttrs)
}
function addGetterSetter(object, target, attrs) {
  function addGetter(object, target, attr) {
    var method = GET + capitalize(attr);
    object[method] = function() {
      return target[method]();
    };
  }
  function addSetter(object, target, attr) {
    var method = SET + capitalize(attr);
    object[method] = function(value) {
      return target[method](value);
    };
  }
  for (var index = 0; index < attrs.length; index++) {
    addGetter(object, target, attrs[index]);
    addSetter(object, target, attrs[index]);
  }
}

吉斯菲德尔