[英]using this keyword with javascript prototype addEventListener
[英]Prototype - addEventListener Click - JavaScript
對於下面編寫的代碼,我需要一些幫助,我需要在單擊時返回該元素,但由於某種原因,它會發回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
});
謝謝
使用
.call(EXPECTED_CONTEXT)
this
在被調用函數中傳遞EXPECTED_CONTEXT
。
嘗試這個:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.