用foreach内部对象创建对象

Create object with foreach inside object

本文关键字:创建对象 内部对象 foreach      更新时间:2023-09-26

有"选项"方法,我发送一个对象作为参数,我希望这个对象被存储在变量answer。代码是:

var Selectable = {
    create: function(type) {
        Object.create(this);
        this.type = type;
        this.id =  Math.random().toString(36).replace(/[^a-z]+/g, '').substring(0, 5);
        this.cacheDom();
        return this;
    },
    cacheDom: function(){
        this.$target = $('#selectable-target');
        this.$id = $('#selectable-' + this.id);
        this.$options = this.$id.find('.selectable-options');
        this.$revise = this.$id.find('a.revise');
    },
    options: function(values){
        this.answers = {};
        Object.keys(values).forEach(function(key) {
            this.answers[key] = values[key];
        });
    },
    render: function() {
        this.$target.append(
            $('<div>')
            .attr('id', 'selectable-'+this.id)
            .append(
                $('<div>')
                .addClass('selectable-options')
            )
        )
        this.cacheDom();
    }
};

当实例化并尝试将控制台中的对象插入到answers属性中时,我得到以下结果:

var test = Selectable.create('img');
undefined
test.options({'foo': '1', 'foo2': '0'});
Uncaught TypeError: Cannot set property 'foo' of undefined(…)
为了解决这个问题,我可以将对象复制到属性中,像这样:
options: function(values){
            this.answers = values;
}

我想知道为什么会发生这种情况,以及如何解决它

错误在

Object.keys(values).forEach(function(key) {
  this.answers[key] = values[key];
});

如果您查看文档,您将看到,当使用forEach时,this在回调中是undefined,除非您传递自定义参数。解决方案是这样重写:

Object.keys(values).forEach(function(key) {
  this.answers[key] = values[key];
}, this);

强制回调的this值等于调用方的this值。

同样地,但仅限于ES6,您可以使用=>而不是function,它捕获this,并且上次我检查(至少是1年前)要快一点:

Object.keys(values).forEach(key => {
  this.answers[key] = values[key];
});

首先,您必须了解什么是Object以及哪个'this'属于哪个实例。在下面这段代码中:

1 options: function(values){ // outer function
2     this.answers = {};
3     Object.keys(values).forEach(function(key) { // inner function
4         this.answers[key] = values[key];
5     });
6 },

第一个'this'(第二行)-链接到外部函数实例。但是第二个"this"——与内部功能相连。不仅如此,没有一个"this"是不链接到Selectable的。

要解决这种混乱-首先你必须将对象作为函数引入。

var Selectable = function() { 

然后将'this'保存到某个变量中。

var that = this;

在你所有的内部函数中使用'that'而不是'this'。

最后,像这样使用Selectable
var selectable = new Selectable();
selectable.options({'foo':'bar'});

希望有所帮助