我越来越熟悉JavaScript的原型世界和this
关键字。我是网络世界的新手。今天,当我开始玩原型时,我看到一些奇怪的行为,但我无法弄清为什么会发生这种情况。我创建了一个构造函数Group
如下:JavaScript:为什么要获取最后插入的值?
// 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
在的script.js的线14我得到以下错误:'类型错误:目标[方法]是不是一个function'。看起来'getName'方法不能像你期望的那样创建。 –
它为我工作。不知道为什么它不适合你。 –