addEventListener中this指向问题


addEventListener绑定事件的时候,事件回调函数里的this应该是指向产生事件的DOM元素,但是可以通过函数绑定修改this指向,特意写了个bind函数,但是不知道为什么不起作用?


 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    hello
</body>
<script type="text/javascript">
    (function(){
        Function.prototype.bind = function() {
        var fn = this, args = Array.prototype.slice.call(arguments), obj = args.shift();
        return function() {
            return fn.apply(obj, args.concat(Array.prototype.slice.call(arguments)));
        };
    };  
    function A() {} 
    A.prototype = {
        addAnimations: function() {
            // console.log("addAnimations");
        },
        animationsHandler: function(e){
            this.out();
        },
        out: function(){
            console.log(1);
        },
        init: function() {
            console.log(this);
            var handler = this.animationsHandler.bind(this);
            document.body.addEventListener('click', this.animationsHandler, false);
            this.addAnimations();
        }
    };
    new A().init();
    })();
    </script>
</html>

this HTML JavaScript

小Queen 9 years, 8 months ago

 init: function() {
    console.log(this);
    var handler = this.animationsHandler.bind(this);
    document.body.addEventListener('click', handler, false);
    this.addAnimations();
}

ljj3388 answered 9 years, 8 months ago

Your Answer