JavaScript:为什么要获取最后插入的值?

JavaScript: Why getting last inserted values?

我越来越熟悉 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是我写的函数,用来给MyGroup.

的属性动态添加getter和setter
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]);
  }
}

现在,当我像这样使用 MyGroupGroup 时:

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() 的组。这是 plunkr

这是因为您要向原型添加方法,并且每次都在循环中覆盖前一个函数,因此当 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]);
  }
}

JSFIDDLE