What underlies this JavaScript idiom: var self = this?

前端 未结 10 1906
长情又很酷
长情又很酷 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:34

    Yes, you'll see it everywhere. It's often that = this;.

    See how self is used inside functions called by events? Those would have their own context, so self is used to hold the this that came into Note().

    The reason self is still available to the functions, even though they can only execute after the Note() function has finished executing, is that inner functions get the context of the outer function due to closure.

提交回复
热议问题