What underlies this JavaScript idiom: var self = this?

前端 未结 10 2135
长情又很酷
长情又很酷 2020-11-22 03:37

I saw the following in the source for WebKit HTML 5 SQL Storage Notes Demo:

function Note() {
  var self = this;

  var note = document.createElement(\'d         


        
10条回答
  •  天命终不由人
    2020-11-22 04:32

    Actually self is a reference to window (window.self) therefore when you say var self = 'something' you override a window reference to itself - because self exist in window object.

    This is why most developers prefer var that = this over var self = this;

    Anyway; var that = this; is not in line with the good practice ... presuming that your code will be revised / modified later by other developers you should use the most common programming standards in respect with developer community

    Therefore you should use something like var oldThis / var oThis / etc - to be clear in your scope // ..is not that much but will save few seconds and few brain cycles

提交回复
热议问题