What is a best practice for ensuring “this” context in Javascript?

后端 未结 8 1466
刺人心
刺人心 2021-02-14 20:37

Here\'s a sample of a simple Javascript class with a public and private method (fiddle: http://jsfiddle.net/gY4mh/).

function Example() {
    function privateFun         


        
8条回答
  •  佛祖请我去吃肉
    2021-02-14 20:57

    In addition to the other answers given here, if you don't have an ES5-ready browser, you can create your own "permanently-bound function" quite simply with code like so:

    function boundFn(thisobj, fn) {
       return function() {
          fn.apply(thisobj, arguments);
       };
    }
    

    Then use it like this:

    var Example = (function() {
        function Example() {
            var privateFunction = boundFn(this, function() {
                // "this" inside here is the same "this" that was passed to boundFn.
                console.log(this);
            });
    
            this.publicFunction = function() {
                privateFunction();
            }
        }
    
        return Example;
    }()); // I prefer this order of parentheses
    

    Voilà -- this is magically the outer context's this instead of the inner one!

    You can even get ES5-like functionality if it's missing in your browser like so (this does nothing if you already have it):

    if (!Function.prototype.bind) {
       Function.prototype.bind = function (thisobj) {
          var that = this;
          return function() {
             that.apply(thisobj, arguments);
          };
       }:
    }
    

    Then use var yourFunction = function() {}.bind(thisobj); exactly the same way.

    ES5-like code that is fully compliant (as possible), checking parameter types and so on, can be found at mozilla Function.prototype.bind. There are some differences that could trip you up if you're doing a few different advanced things with functions, so read up on it at the link if you want to go that route.

提交回复
热议问题