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

后端 未结 8 1425
刺人心
刺人心 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条回答
  •  梦毁少年i
    2021-02-14 21:02

    Using closure. Basically any variable declared in function, remains available to functions inside that function :

    var Example = (function() {
        function Example() {
            var self = this; // variable in function Example
            function privateFunction() {                  
                // The variable self is available to this function even after Example returns. 
                console.log(self);
            }
    
            self.publicFunction = function() {
                privateFunction();
            }
        }
    
        return Example;
    })();
    
    ex = new Example;
    ex.publicFunction();
    

提交回复
热议问题