gpt4 book ai didi

javascript - 如何在javascript中封装数据而不在每个对象实例中重复函数?

转载 作者:行者123 更新时间:2023-11-30 11:55:07 25 4
gpt4 key购买 nike

我在 JavaScript 中创建了一个具有公共(public)和私有(private)属性的类 - 数据和操作这些数据的方法。某些数据是私有(private)的,不应通过类实例中的“.”(点)运算符访问。有没有办法避免每个类实例的方法重复?

function MyClass() {
let privateVar;
let publicVar;
function publicFun() {
// do something
}
function privateFun(){
// do something else
}
this.v = publicVar;
this.f = publicFun;
}

let obj1 = new MyClass();
let obj2 = new MyClass(); // publicFun and privateFun methods duplication

ClassName.prototype 方法需要所有类数据的完全公共(public) API。所以这对我不起作用。

最佳答案

如果我理解正确的话,这是我的例子:

  1. 方法只在包装函数中定义一次(因此它们不会在每个实例上声明)
  2. 您可以创建对象的实例,它们都将引用相同的方法,并且可以公开数据。

Here是一个 fiddle 的例子:

function wrapper() {
//Methods defined only once
function method() {
alert("this is method");
}

function methodWithParams(param, callback) {
var paramsVar = param;

function realMethodHere() {
alert("We passed a param: " + paramsVar);
paramsVar = "Changed"
callback(paramsVar);
alert("Now we cahnged the param's value to: " + paramsVar + ", rerun the method to verify");
}

return realMethodHere;
}

//Class constructor
function classConstructor() {
//Private
var privateData = "Private"

function privateFunction() {
alert("this is some private function, inaccesible");
}

//This callback was addedto allow yo uto change private data.
function privateDataChangerCallback(param) {
privateData = param;
}


//Public
this.publicData = "Public"
this.callMethod = method;
this.paramMethod = methodWithParams(privateData, privateDataChangerCallback);
}


return classConstructor;
}

var classDefinition = wrapper();
var classInstance = new classDefinition();

classInstance.callMethod(); //method without param
classInstance.paramMethod(); //method with exposed Private data
//rerunning the method to see what the value is:
classInstance.paramMethod(); //method with exposed Private data

关于javascript - 如何在javascript中封装数据而不在每个对象实例中重复函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38243603/

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