JavaScript private methods

前端 未结 30 1962
-上瘾入骨i
-上瘾入骨i 2020-11-22 08:16

To make a JavaScript class with a public method I\'d do something like:

function Restaurant() {}

Restaurant.prototype.buy_food = function(){
   // something         


        
30条回答
  •  眼角桃花
    2020-11-22 09:05

    Using self invoking function and call

    JavaScript uses prototypes and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.

    Wikipedia quote:

    Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; when a function is called as a method of an object, the function's local this keyword is bound to that object for that invocation.

    Solution using a self invoking function and the call function to call the private "method" :

    var MyObject = (function () {
    
        // Constructor
        function MyObject (foo) {
            this._foo = foo;
        }
    
        function privateFun (prefix) {
            return prefix + this._foo;
        }
    
        MyObject.prototype.publicFun = function () {
            return privateFun.call(this, '>>');
        }
    
        return MyObject;
    })();
    
    
    var myObject = new MyObject('bar');
    myObject.publicFun();      // Returns '>>bar'
    myObject.privateFun('>>'); // ReferenceError: private is not defined
    

    The call function allows us to call the private function with the appropriate context (this).


    Simpler with Node.js

    If you are using node.js, you don't need the IIFE because you can take advantage of the module loading system:

    function MyObject (foo) {
        this._foo = foo;
    }
    
    function privateFun (prefix) {
        return prefix + this._foo;
    }
    
    MyObject.prototype.publicFun = function () {
        return privateFun.call(this, '>>');
    }
    
    exports.MyObject = MyObject;
    

    Load the file:

    var MyObject = require('./MyObject').MyObject;
    
    var myObject = new MyObject('bar');
    myObject.publicFun();      // Returns '>>bar'
    myObject.privateFun('>>'); // ReferenceError: private is not defined
    


    (experimental) ES7 with the Bind Operator

    The bind operator :: is an ECMAScript proposal and is implemented in Babel (stage 0).

    export default class MyObject {
      constructor (foo) {
        this._foo = foo;
      }
    
      publicFun () {
        return this::privateFun('>>');
      }
    }
    
    function privateFun (prefix) {
      return prefix + this._foo;
    }
    

    Load the file:

    import MyObject from './MyObject';
    
    let myObject = new MyObject('bar');
    myObject.publicFun();      // Returns '>>bar'
    myObject.privateFun('>>'); // TypeError: myObject.privateFun is not a function
    

提交回复
热议问题