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
是我编写的函数,用于将 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]);
}
}
吉斯菲德尔
相关文章:
- 从数据库中获取数据并插入JavaScript变量
- 如果数字已插入排序数组,则获取该数字的索引
- 获取插入符号相对于行可见起点的位置
- 如何使用Jscript | JQuery在textArea中获取插入的|删除的字符串的索引和长度
- 获取每种语言的跨度标题,并插入新的跨度中
- Meteor:从Twilio获取SMS文本列表,并将它们插入mongoDB
- 通过 Yii2 表单插入数据时获取空值
- 谷歌表格-从硬盘获取文件名并插入表格-(模拟Excel's Appification.GetOpenFilena
- 如何使用javascript获取&使用字符偏移量设置插入符号位置
- 如何获取复选框值并将其插入到挖空中的可观察数组中
- 在数据库中插入之前获取UID主键
- 在插入符号位置获取DOM元素
- 单击时获取文本区域中插入符号的位置
- 我想单击一个
- 并获取 id 以通过 POST 将其插入数据库,可以吗?
- 如何获取插入到表中的行的自动生成的ID
- json - 从响应对象中获取值,并将其插入请求中
- 获取具有最高值的变量,并将该变量的名称插入到输入中
- 获取动态插入的当前 js 文件路径
- Javascript open.window 获取字段值,然后将值插入父窗口
- SQLite web应用程序,从插入获取行