オブジェクトをパラメータとして送信し、このオブジェクトを変数answer
に保存するオプションのメソッドがあります。コードは次のとおりです。オブジェクト内にforeachを持つオブジェクトを作成する
var test = Selectable.create('img');
undefined
test.options({'foo': '1', 'foo2': '0'});
Uncaught TypeError: Cannot set property 'foo' of undefined(…)
問題を解決するために、私はちょうどにオブジェクトをコピーすることができます:
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();
}
};
インスタンス化として
と回答プロパティにコンソールでオブジェクトを挿入しようと、私はこれを取得しますこのようなプロパティ:
options: function(values){
this.answers = values;
}
なぜこれが起こっているのか、それを修正する方法を知りたいのですが。 forEach
を使用しているときにカスタム引数を渡さない限り、あなたはthe documentationを見れば、エラーが
Object.keys(values).forEach(function(key) {
this.answers[key] = values[key];
});
である
を役に立てば幸い'がグローバルウィンドウオブジェクトになります。これは、 'Selectable.create()'を呼び出すときに起こっていることです – jcbp
@jcbp:いいえ 'Selectable.create()'は 'this'のために' Selectable'を使って 'create'関数を呼び出します - それはメソッド呼び出しです! – Bergi
@Bergiはい、そうです。すみません、私の間違いです。 – jcbp