我很难在JS中围绕变量范围。有没有办法访问使用对象工厂创建的对象的实例变量,类似于下面的示例?
function Renderer(id, options) {
var id = id;
var options = options;
return {
render: function(selector) {
$(selector).each(function(index) {
this.renderOptions(); //This does not reference the Renderer, but the html element selected by jQuery.
});
},
renderOptions: function() {
console.log(this.options);
}
}
}
var myRenderer = new Renderer('test', [1, 2, 3, 5, 8, 13]);
答案 0 :(得分:1)
您只需要保留对象的命名引用,因为this
在每次方法调用时都被重新定义,并且通常指向回调内部的错误上下文:
var instance = {
render: function(selector) {
$(selector).each(function(index) {
instance.renderOptions();
});
},
...
}
return instance;
答案 1 :(得分:0)
修改后的代码
function Renderer(id, options) {
var id = id;
var options = options;
return {
render: function(selector) {
var self = this;
$(selector).each(function(index) {
self.renderOptions(); // here this is a reference of dom element.
});
},
renderOptions: function() {
console.log(this.options);
}
}
}
答案 2 :(得分:0)
由于var options...
属于Renderer
范围,因此您只需在options
函数内使用renderOptions
。
您还需要像其他海报所提到的那样创建对this
的引用。
function Renderer(id, options) {
var id = id;
var options = options;
return {
render: function(selector) {
var self = this;
$(selector).each(function(index) {
self.renderOptions();
});
},
renderOptions: function() {
console.log(options);
}
}
}
而且,如果我正确地阅读了此代码的意图,您可能希望将对该元素的引用传递给renderOptions
函数:
function Renderer(id, options) {
var id = id;
var options = options;
return {
render: function(selector) {
var self = this;
$(selector).each(function(index) {
self.renderOptions(this);
});
},
renderOptions: function(ele) {
$(ele).css(options); // or whatever you plan to do.
}
}
}