gpt4 book ai didi

javascript - 从每个实例都有一个私有(private)闭包的模块导出一个类,但它的原型(prototype)链仍然可以扩展?

转载 作者:行者123 更新时间:2023-11-30 17:04:03 26 4
gpt4 key购买 nike

f.e.假设我有

function foo() {
var privateVariable = "foo"
return class Foo {
constructor() {
// do something with privateVariable
}
}
}
export default foo

所以我将导出返回一个类的函数,然后该类的每个实例都会有一个从调用该函数以获取该类时开始的闭包。然后我可以做

import foo from "Foo"
var instance = new (foo())()

每个实例都由一个返回的类组成,因此每个实例的原型(prototype)都有一个私有(private)闭包(是的,这不是最有效的,因为每次都返回一个新的类定义)。问题是扩展类意味着从 Foo 扩展的每个实例将共享一个闭包,f.e.

var Foo = foo() // get a new class definition
class Bar extends Foo {
// ...
}

现在每次我创建一个 new Bar() 时,它的原型(prototype)都是 Foo,但是每个扩展 Foo 原型(prototype)的类都将共享相同的私有(private)闭包(基本上私有(private)变量现在是静态的) 因为不是每次都获取新的 Foo 定义。

我如何使 Foo 可扩展,以便每个 new Bar() 的 Foo 原型(prototype)都有一个私有(private)闭包?

编辑 2015 年 2 月 7 日上午 12:53: 有趣的是,我提出了自己的解决方案,这恰好类似于使用 Wea​​kMap 的公认答案,除了它只是一个 map ,而不是弱 map :

//
// --- PrivateManager.js
//
function PrivateManager() { // singleton
this.instances = []
this.instanceData = {}
this.currentId = 0
}
PrivateManager.prototype.__register = function(instance, instanceDatum) {
if (this.instances.indexOf(instance) === -1) {
this.instances[this.currentId] = instance
this.instanceData[this.currentId] = instanceDatum
this.currentId++
}
}
PrivateManager.prototype.__getMethod = function(desiredMethod) {
return this[desiredMethod]
}

//
// --- Person.js
//
function PersonPrivateManager() {
var mngr = this
this.getName = function() {
return mngr.instanceData[mngr.instances.indexOf(this)].name
}
}
PersonPrivateManager.prototype = new PrivateManager()

var privateMngr = new PersonPrivateManager()
function Person(name) {
privateMngr.__register(this, {
name: name
})
}
Person.prototype.getName = privateMngr.__getMethod("getName")

//
// --- app.js
//
var person1 = new Person('Bentra')
console.log(person1.getName()) // Bentra
console.log(person1.name) // undefined

var person2 = new Person('Amadar')
console.log(person2.getName()) // Amadar
console.log(person2.name) // undefined

console.log(person1.getName === person2.getName) // true, references to the same function, no memory waste as far as duplicate functions go.

缺点是它不会像 WeakMap 那样自动进行垃圾回收。这是一个冲动的解决方案。它可以被修改以模仿 WeakMap 的更简洁的 API,减去垃圾收集。

最佳答案

只需为您的 Bar 类做同样奇怪的事情:

import foo from "Foo"
function bar() {
var Foo = foo();
return class Bar extends Foo {
constructor() {
}
}
}
export default bar

关于javascript - 从每个实例都有一个私有(private)闭包的模块导出一个类,但它的原型(prototype)链仍然可以扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28336845/

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