What underlies this JavaScript idiom: var self = this?

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

    See this article on alistapart.com. (Ed: The article has been updated since originally linked)

    self is being used to maintain a reference to the original this even as the context is changing. It's a technique often used in event handlers (especially in closures).

    Edit: Note that using self is now discouraged as window.self exists and has the potential to cause errors if you are not careful.

    What you call the variable doesn't particularly matter. var that = this; is fine, but there's nothing magic about the name.

    Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.

    For example, a simple event callback:

    function MyConstructor(options) {
      let that = this;
    
      this.someprop = options.someprop || 'defaultprop';
    
      document.addEventListener('click', (event) => {
        alert(that.someprop);
      });
    }
    
    new MyConstructor({
      someprop: "Hello World"
    });

提交回复
热议问题