2011-08-30 64 views
0

我正在创建一个小型工具提示应用程序,并且遇到了问题。我试图给文档添加一个事件,但是在引用需要执行的函数时遇到了问题。下面是代码:如何使用'this'关键字进行函数引用

var Note, note; 
(function() { 
    'use strict'; 

    // Helper functions 
    function addEvent(to, type, fn) { 
     if (to.addEventListener) { 
      to.addEventListener(type, fn, false); 
     } else if (to.attachEvent) { 
      to.attachEvent('on' + type, fn); 
     } else { 
      to['on' + type] = fn; 
     } 
    } 

    // Temporary constructor 
    function Temp() { 
     this.dragging = false; 

     return this; 
    } 

    Temp.prototype = { 
     listen: function() { 
      this.dragging = true; 
     }, 
     drag: function() { 
      alert('hi 1'); 
      if (!this.dragging) return; 
      alert('hi 2'); 
     }, 
     create: function() { 
      // unimportant code ... 

      addEvent(document, 'mousedown', this.drag); 

      // unimportant code ... 
     } 
    }; 

    window.Note = Temp; 
}()); 

note = new Note(); 
note.create(); // the note is created as planned 
note.listen(); // alert(note.dragging) yields true 

如果在代码中的小失误,我不认为这些都是问题,在我的系统代码通过JSLint的(我知道这并不能保证正确性)。这两种警报都没有提醒他们的论点。不过,我怀疑问题在于将this.drag分配给事件处理程序的函数引用。有没有解决这个问题的方法?

谢谢大家的时间!

+0

你的代码工作正常,在我的IE9,Chrome和Firefox。 –

+0

@Robby,D:没办法,我在用镀铬。 。 。 > _> – dunnza

回答

1

尝试下一个:

(function() { 
    'use strict'; 

// Helper functions 
function addEvent(to, type, fn) { 
    if (to.addEventListener) to.addEventListener(type, fn, false); 
    else if (to.attachEvent) to.attachEvent('on' + type, fn); 
    else to['on' + type] = fn; // this is bad. this do not support multiple handlers 
} 

// Temporary constructor 
function Temp() { 
    this.dragging = false; 
} 

Temp.prototype = { 
    constructor: Temp, // needed because it is removed when used Temp.prototype={...} 
    listen: function() { 
     this.dragging = true; 
    }, 
    drag: function() { 
     alert('hi 1'); 
     if (!this.dragging) return; 
     alert('hi 2'); 
    }, 
    create: function() { 
     //addEvent(document, 'mousedown', this.drag); 
     addEvent(document, 'mousedown', this.drag.bind(this)); 
     // or in older maner (when .bind() not implemented): 
     //var self=this; 
     //addEvent(document, 'mousedown', function(){self.drag();}); 
    } 
}; 

window.Note = Temp; 
})(); 

var note = new Note(); 
note.create(); // the note is created as planned 
note.listen(); // alert(note.dragging) yields true 
+0

非常感谢您! * bind *属性就像一个魅力!我将不得不在mdn上查看它。 – dunnza

+0

.bind未在某些浏览器中实现(例如,IE8或更低版本)。如果你想解决它:使用JavaScript实现该功能:请参阅_Compatibility section_在https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind –