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

后端 未结 8 1427
刺人心
刺人心 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:55

    I guess most used way to get this done is by simply caching (storing) the value of this in a local context variable

    function Example() {
        var that = this;
        // ...
        function privateFunction() {
            console.log(that);
        }
    
        this.publicFunction = function() {
           privateFunction();
        }
    }
    

    a more convenient way is to invoke Function.prototype.bind to bind a context to a function (forever). However, the only restriction here is that this requires a ES5-ready browser and bound functions are slightly slower.

    var privateFunction = function() {
        console.log(this);
    }.bind(this);
    

提交回复
热议问题