onClick Function “this” Returns Window Object

后端 未结 5 1490

I\'ve come across a head scratching issue with my JavaScript application.

If I write an element like this:

  • 5条回答
    •  抹茶落季
      2020-12-01 10:08

      If you are new to JavaScript do not use the this or new keyword, because either you will get it wrong or your code will be unnecessarily inefficient and more complex. What you are trying to accomplish, though is the following:

    • some text
    • In that example the click event of that list item fires a function named foo. The this keyword is passed in as a variable. The this keyword merely refers to the entity that called the function in question and if it cannot find that entity it will refer to the window object of the browser. In this case the entity that called the function is the list item node from the DOM.

      I still suggest never using this keyword in order to avoid this kind of confusion moving forward.

      EDIT: Also, do not use a tagName property as this is not standard. Instead use the nodeName property.

    提交回复
    热议问题