4

我是 JavaScript 新手,我正试图用私有数据和公共函数创建“类”。我被告知立即调用函数表达式 (IIFE) 可以完成此操作,但是当我从类中“实例化”新对象时,它们会引用私有数据而不是拥有自己的数据。

其中一些是从Create a JS class 中借来的:IIFE vs return prototype

例如,一个简单的汽车“类”:

var Car = (function() {

    var body = { color: 'red' };
    Car.prototype.newColor = function(color) {
            body.color = color;
        };
    Car.prototype.getColor = function() {
            return body.color;
        };

    return Car;
})();

var car1 = new Car();
var car2 = new Car();

car2 的颜色也变为紫色。

car1.newColor('purple');
car2.getColor(); // 'purple'

我希望 Car 类的每个对象都保存自己的私有数据。IFFE如何实现这一点,或者有其他方法吗?

4

3 回答 3

3

模拟私有实例变量的唯一方法是将它们声明为var myprivate在构造函数中。

任何特权方法(=可以访问私有成员的方法)也必须在构造函数的主体中声明,因此不能在原型上(将花费您额外的 cpu 和内存,并且可能在某些情况下也不会优化JS 引擎)。

我从来没有遇到过需要这样做的情况,因为在我看来,付出的代价不值得。通常向我未来的自己和其他程序员表明,一个成员通过广泛使用的命名约定是私有的(名称以下划线开头)_myPrivate

“公共覆盖”的回答启发了我创建以下代码。私有实例成员可以被公开访问,ben._data.set或者您可以重新实施规则和/或 getter/setter,以便有人仍然可以滥用它。它仍然可以清理您是对象的可公开访问的成员,并使其更容易使用 getter 和 setter。

//Namespacing DataStore to limit scope of the closures
var tools = {
  DataStore : function(){
    var store = [];
    this.get = function(key){
      return store[key];
    };
    this.set = function(key,value){
      store[key] = value;
      return value;
    };
  }
};
//Person constructor
var Person = function(name){
  //you can access this member directly
  // bob.name = "Lucy";
  this.name=name;
  //if having _data as not accesable by defining
  //  with var _data we whould have to define
  //  get and set here as this.get and this.set
  this._data=new tools.DataStore();
};
//constant value used to get or set, for example:
//ben.get(ben.AGE);
//Could add this and rules to Person instead of Person.prototype
//then you'll need a helper function to set up inheritance
//to make sure the static's on Person are copied to it's children
Person.prototype.AGE=0;
//rules for getters and setters
//Will be a problem with inheritance if on prototype 
//function Employee(name){Person.call(this,name);};
//Employee.prototype=Object.create(Person.prototype);
//Employee.prototype.rules["0set"]=..overwrites Person.prototype.rules["0set"]
//When inheriting you need to have a helper function set the rules for a child
//object
Person.rules = {}
//rule for AGE set
Person.rules[Person.prototype.AGE+"set"] = function(val){
  var tmp;
  tmp = parseInt(val);
  if(isNaN(tmp)){
    throw new Error("Cannot set the age of the person "+
      "to non number value, value of age:"+val);
  }
  if(tmp>150){
    throw new Error("Are you sure this is a person and "+
      "not a turtule? Trying to set age to:"+val);
  }
  return this._data.set(this.AGE,tmp);
};
//rule for age get
Person.rules[Person.prototype.AGE+"get"] = function(){
  return this._data.get(this.AGE);
};
Person.prototype.get = function(key){
  return Person.rules[key+"get"].call(this);
};
Person.prototype.set  = function(key,value){
  return Person.rules[key+"set"].call(this,value);
};

var ben = new Person("Ben");
ben.set(ben.AGE,22);
console.log(ben.get(ben.AGE));
try{
  ben.set(ben.AGE,151);
}catch(e){
  console.log("error",e);
}
try{
  ben.set(ben.AGE,"HELLO WORLD!");
}catch(e){
  console.log("error",e);
}

注意事项:Person.rules需要从 Person 继承时复制到 Child 实例。

更多关于原型,继承,覆盖,调用超级,多重继承(混合)和this这里的价值:https ://stackoverflow.com/a/16063711/1641941

于 2013-11-09T17:10:08.477 回答
1
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
//
于 2013-11-09T19:19:58.493 回答
1

但是这样你.privilegedMethod()每次创建一个对象时定义,并且每个对象都将持有不同版本的(相同目的)方法......

我想出的解决方案是使用对象到对象(私有)hashmap,并将新创建的对象映射到ctor函数中的相应数据,并使用hasmap作为“管理器”来确定哪些数据对应于哪个对象,在原型方法中,像这样:

var Car = 
( function ( hashmap ) {

  function PrivateClassCarData ( c, t ) {
    this.color = c;
    this.type  = t;
  }

  function Car ( color, type ) {
    hashmap.place( this, new PrivateClassCarData( color, type ) );
  }

  // read
  Car.prototype.getColor =
  function () {
    return hashmap.read( this ).color;
  };

  // write
  Car.prototype.setColor =
  function (c) {
    hashmap.read( this ).color = c;
    return this;
  };

  // weak point, memory leak source
  // dereference object from hash-map before updating variable that points to it
  // another reference is kept in hashmap
  // @TODO, automatic dereferencing execution, anybody?
  Car.prototype.mfree =
  function () {
    hashmap.drop( this );
    return this;
  };

  return Car;

} )(

  // basic hash-map implementation
  // maps objects to objects
  ( function ( hk, hv ) {

    return {

      place : function ( objKey, objVal ) {
        hk.push( objKey );
        hv.push( objVal );
        return this;
      },

      read  : function ( objKey ) {
        return hv[ hk.indexOf( objKey ) ];
      },

      drop  : function ( objKey ) {
        var pos;
        ( ( pos = hk.indexOf( objKey ) ) != -1 )
        && (
          hk.splice( pos, 1 ),
          hv.splice( pos, 1 )
        );
        return this;
      }

    };

  } )( [], [] )

);

var c1 = new Car("red","ferrary");
var c2 = new Car("white","porche");

c1.getColor();
// red

c2.setColor("silver");

c1.getColor();
// red

c2.getColor();
// silver
//
于 2013-11-09T18:07:08.947 回答