2016-03-01 77 views
0

我需要一些帮助,下面的代码是我写的,我需要在点击返回的元素,但由于某种原因,它发回的窗口对象,而不是HTML元素原型 - 的addEventListener点击 - JavaScript的

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 

    }); 

感谢

+0

似乎在这个小提琴的工作:https://jsfiddle.net/mgtqsxv7/ –

回答

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>

+0

感谢这么多的快速反应! – Rizo

相关问题