Create a class with IIFE that isn't a reference?

后端 未结 3 491
耶瑟儿~
耶瑟儿~ 2020-12-19 16:53

I\'m new to JavaScript and I\'m trying to wrap my head around creating \"classes\" with private data and public functions. I\'ve been told Immediately Invoked Function Expre

3条回答
  •  孤城傲影
    2020-12-19 17:59

    var Car = 
    ( function ( cardb ) {
    
      function Car ( color ) {
    
        // facing the same problem here
        // reinstaling .data() method for each created object
        // but this way each has its own data store object
        // and inner 1 to 1 circular reference js is able to deal with
        cardb( this );
    
        // set provided color parameter
        this.data("color", color);
    
      }
    
      return Car;
    
    } )(
    
      // function to install .data() method to given object
      // it gets attached to object directly, instead of
      // attaching it to .prototype, in which case all
      // object will access same data store
      function ( obj ) {
    
        var _data = {};
    
        obj.data =
        function ( name, value ) {
          return arguments.length
           ? (
            ( value == null )
             ? _data[name]
             : (
               _data[name] = value,
               this
             )
           )
           : _data;
        };
    
        return obj;
    
      }
    );
    
    var c1 = new Car("red");
    var c2 = new Car("blue");
    
    c1.data("color");
    // red
    
    c2.data("color");
    // blue
    
    c1.data("color","white");
    
    c2.data("color");
    // blue
    c1.data("color");
    // white
    //
    

提交回复
热议问题