我熟悉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()
的组。这是plunkr
答案 0 :(得分:3)
这是因为您正在为原型添加方法,并且每次上一个函数都在循环中覆盖,因此当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 强>