Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/462.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 访问';这';每个循环内的对象属性_Javascript_Mootools - Fatal编程技术网

Javascript 访问';这';每个循环内的对象属性

Javascript 访问';这';每个循环内的对象属性,javascript,mootools,Javascript,Mootools,在foreach循环中访问testval和testoption的最佳方式是什么?这是一份草稿 var some = new Class({ options: { testarray: [1,2,3], testoption: 6 }, initialize: function(options) { this.testval = '123'; this.options.testarray.each(function(el) {

在foreach循环中访问testval和testoption的最佳方式是什么?这是一份草稿

var some = new Class({
   options: { testarray: [1,2,3], testoption: 6 },       
   initialize: function(options) {
      this.testval = '123';
      this.options.testarray.each(function(el) { 
         console.log(this.testval);
         console.log(this.options.testoption);
      });
    } 
});
更新:
我可以通过在数组上添加bind(this)来修复它,但这就是解决方法吗?

如果我需要从函数中引用大量实例变量,使得
this
引用我经常使用的其他东西
var self=this就在前面。我发现它读起来比到处装订要好得多;
self
变得明确,可以引用实例。

是的,mootools实现这一点的方法是使用

this.options.testarray.each(function(el) { 
  console.log(this.testval);
  console.log(this.options.testoption);
}.bind(this));
或者使用
Binds
mutator(Mootools提供更多信息,谢谢@Dimitar Christoff)

我将each(而不是forEach,如注释中所述)移到initialize()中,因为我不确定类描述符对象中的代码是否有效。。。另外,您可能希望使用initializewith
this.setOptions(options)
中传递的选项,并实现options mutator


此外,正如您在每条评论中所指出的,
var self=this非常方便且可读。

mootools的方法是使用.each(api)而不是.forEach(不在旧ie中)。fn后的第二个参数是上下文。但是这是大多数人的首选。啊,是的,我甚至没有注意到这一点。。。最正确的方法是使用
self=this
方法。我对绑定有一个弱点,尤其是因为当时我很难理解它。但是,一旦我消除了所有错误,这个方法仍然有效:)是的,当原生fn.proto.bind时,完全绑定是非常好的,但是我不喜欢
绑定mutator
的可读性。和我不喜欢的一样。bindAll
,需要作为一种模式死去!你应该把它改成一个
mootools更多的东西。
var some = new Class({
 options: { testarray: [1,2,3], testoption: 6 },
 Implements: Optons,
 Binds: ['logOption'],
 initialize: function(options) {
   this.testval = '123';
   this.setOptions(options);
   this.options.testarray.each(this.logOptions);
 },
 logOptions : function(value, index, array) {
   // I don't really see the point, but here you are, this code will be executed
   // three times, with (1, 0, [1,2,3]), (2, 1, [1,2,3]) and (3, 2, [1,2,3])
   console.log(value, index, array);
   console.log(this.testval);
   console.log(this.options.testoption);
 }
});