this参照2

by s_hiroshi

HTML

<p id="foo">Foo</p>
<p id="bar">Bar</p>

JavaScript

var Foo = function() {
    this.id = 'Foo';
    this.func = function() {
        console.log(this.id); // Fooではなくfoo
    };
    document.getElementById('foo').addEventListener('click', this.func, false);
};
new Foo();

var Bar = function() {
    this.id = 'Bar';
    this.func = function() {
        console.log(this.id); // barではなくBar
    }
    document.getElementById('bar').addEventListener('click', this.func.bind(this), false);
}
new Bar();