gpt4 book ai didi

javascript - 使用 IIFE 创建一个不是引用的类?

转载 作者:行者123 更新时间:2023-11-29 17:13:45 25 4
gpt4 key购买 nike

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

部分借自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 类的每个对象都拥有自己的私有(private)数据。这如何通过 IFFE 实现,或者有其他方法吗?

最佳答案

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

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

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

“公共(public)覆盖”的回答启发了我创建以下代码。私有(private)实例成员可以通过 ben._data.set 公开访问,或者您可以重新实现规则和/或 getters/setters 以便有人仍然可以滥用它。它仍然可以清理您是对象的可公开访问的成员,并使其更容易使用 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 实例。

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

关于javascript - 使用 IIFE 创建一个不是引用的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19878346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com