What underlies this JavaScript idiom: var self = this?

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

    It should also be noted there is an alternative Proxy pattern for maintaining a reference to the original this in a callback if you dislike the var self = this idiom.

    As a function can be called with a given context by using function.apply or function.call, you can write a wrapper that returns a function that calls your function with apply or call using the given context. See jQuery's proxy function for an implementation of this pattern. Here is an example of using it:

    var wrappedFunc = $.proxy(this.myFunc, this);

    wrappedFunc can then be called and will have your version of this as the context.

提交回复
热议问题