Prototype - addEventListener Click - JavaScript

时间:2016-03-01 07:37:54

标签: javascript click prototype addeventlistener

我需要一些关于我编写的代码的帮助,我需要在点击时返回元素但由于某种原因它会发回 Window 对象而不是 HTMLElement

HTML

<div id="myDiv">Click me!</div>

的JavaScript

   function myP(selector) {
        if (!(this instanceof myP)) {
            return new myP(selector);
        }

        this.elem = document.querySelector(selector);
    }        

    myP.prototype = {
        click : function(objF){
            this.elem.addEventListener("click", function(){
                objF();
                console.log(this); //Returns the Element ( <div id="myDiv"> )
                return this; // Doesn't work
            }, false);
        }
    }

    myP("#myDiv").click(function(){
        console.log(this); // Returns [object Window]

        // I want to return: ( <div id="myDiv"> ) Element here

    });

由于

1 个答案:

答案 0 :(得分:1)

  

使用.call(EXPECTED_CONTEXT)在调用函数中将EXPECTED_CONTEXT作为this传递。

试试这个:

function myP(selector) {
     if (!(this instanceof myP)) {
       return new myP(selector);
     }

     this.elem = document.querySelector(selector);
   }

   myP.prototype = {
     click: function(objF) {
       this.elem.addEventListener("click", function() {
         objF.call(this);
         return this;
       }, false);
     }
   }

   myP("#myDiv").click(function() {
     console.log(this);
   });
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<div id="myDiv">Click me!</div>