簡體   English   中英

如何在 class 的方法內的事件偵聽器中使用“this”關鍵字,而不會失去對 class arguments 和方法 ZDBC11CAA5BDA99F77E6FBDABDBDBDA99F77E6FBDABDBD77 的訪問權限

[英]How to use “this” keyword inside event listener inside a method of a class without losing access to class arguments and method arguments?

我正在嘗試學習在各種上下文中使用“this”關鍵字,到目前為止,我發現的所有資源,包括在 stackoverflow 中提出的類似問題,都讓我感到困惑。 其中包括一些使用.bind 和.proxy 方法的方法。 希望有人對如何解決附加代碼片段的評論中描述的問題有更清晰的解釋。

 class Entity { constructor(entityArgs) { this.entityArgs = entityArgs; } method(methodArgs) { $('.button').on('click', function(event) { event.preventDefault(); // Should return the button clicked. Codes seem to work $('#result').append('<br> clicked: ' + $(this).text() + '<br>'); // Should return 'testMethodArg' as per below. Codes seem to work $('#result').append('methodArgs: ' + methodArgs + '<br>'); // Should return 'testEntityArg' as per below. NOT WORKING - this is the problem $('#result').append('entityArgs: ' + this.entityArgs + '<br>'); }) } } $(function() { const obj = new Entity('testEntityArg'); obj.method('testMethodArg'); })
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <script src="https.//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <title>Document</title> </head> <body> <div> <button id=tgtButton1 class="button"> Button1 </button> </div> <br> <div> <button id=tgtButton2 class="button"> Button2 </button> </div> <div id='result'> </div> </body> </html>

jquery 的on() function 中的this關鍵字將引用 DOM 元素button 如果需要訪問this的父級上下文,可以將其放入變量中。

 class Entity { constructor(entityArgs) { this.entityArgs = entityArgs; } method(methodArgs) { var entity_this = this; $('.button').on('click', function(event) { console.log("this keyword from inside function: "); console.log(this); console.log("this keyword from parent class: "); console.log(entity_this); event.preventDefault(); // Should return the button clicked. Codes seem to work $('#result').append('<br> clicked: ' + $(this).text() + '<br>'); // Should return 'testMethodArg' as per below. Codes seem to work $('#result').append('methodArgs: ' + methodArgs + '<br>'); // Should return 'testEntityArg' as per below. NOT WORKING - this is the problem $('#result').append('entityArgs: ' + entity_this.entityArgs + '<br>'); }) } } $(function() { const obj = new Entity('testEntityArg'); obj.method('testMethodArg'); })
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <script src="https.//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <title>Document</title> </head> <body> <div> <button id=tgtButton1 class="button"> Button1 </button> </div> <br> <div> <button id=tgtButton2 class="button"> Button2 </button> </div> <div id='result'> </div> </body> </html>

框“這個”

這是另一個稍微復雜的用法。 我為自己做的只是為了玩“這個”。 我希望它有助於闡明“這個”

 const boxes = document.querySelectorAll('div') const keys = Object.keys(boxes); //4 const boxArray = [] const boxArrayDotFrom = Array.from(boxArray) boxes.forEach((boxes, i) => { boxes.addEventListener('click', function logStyle() { let w = this.clientWidth; let h = this.clientHeight; let style = getComputedStyle(this) let c = style.backgroundColor let index = i if (boxArray === 0) { boxArray.push(i) } else { boxArray.shift() boxArray.push(i) } this.nextElementSibling.innerHTML = ` Next Sibling of box # ${index}<br>` this.innerHTML += ` THIS is index # ${index} ` this.innerHTML += `<strong>boxArray</strong> = ${boxArray} ` this.innerHTML += `<br> 'listener', 'H', ${h}, 'W', ${w}, 'Color', ${c}` console.log('', this.textContent) console.log('boxArray', boxArray) console.log('listener', 'H', h, 'W', w, 'Color', c) }); }, this);
 body, html { font: 1.1rem system-ui; background-color: yellow; display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); grid-gap: 10px; } div { padding: 10px 0; transition: all ease-in-out 1s; cursor: crosshair; }.box3 { min-height: 50px; background-color: red; }.box0 { /* width: 75px; */ min-height: 60px; background-color: green; }.box1 { /* width: 100px; */ min-height: 70px; background-color: blue; }.box2 { min-height: 100px; background-color: dodgerblue; }
 <div id='click' class='box3'> <!-- <p> </p> --> </div> <div class='box0'> <p> </p> </div> <div class='box1'> <p> </p> </div> <div class='box2'> <p> </p> </div>

"$('#result').append('entityArgs: ' + this.entityArgs + ' 中的 "this" 的結果
')" 綁定到返回的 ".button" DOM object,this.entityArgs 在 DOM 對象上不存在,因此調用 this.entityArgs 產生未定義。要獲取對實體 class 的引用,您可以將其存儲在方法 function。您可以使方法 function 看起來像這樣:

method(methodArgs){
      let entityArgs = this.entityArgs
    $(".button").on("click", function (event) {
      event.preventDefault();
      // Should return the button clicked. Codes seem to work
      $("#result").append("<br> clicked: " + $(this).text() + "<br>");
      // Should return 'testMethodArg' as per below . Codes seem to work
      $("#result").append("methodArgs: " + methodArgs + "<br>");
      // Should return 'testEntityArg' as per below. NOT WORKING - this is the problem
      $("#result").append("entityArgs: " + entityArgs + "<br>");
    });
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM