gpt4 book ai didi

javascript:我可以使用原型(prototype)定义一个 "private"变量吗?

转载 作者:行者123 更新时间:2023-12-04 09:40:44 24 4
gpt4 key购买 nike

我想为每个“实例”使用一个唯一的私有(private)变量(我希望这是 Javascript 中的正确术语),但两个实例似乎都使用相同的私有(private)变量。

func = function(myName)
{
this.name = myName
secret = myName

func.prototype.tellSecret = function()
{ return "the secret of "+this.name+" is "+secret
}
}

f1 = new func("f_One")
f3 = new func("f_3")

console.log(f3.tellSecret()) // "the secret of f_3 is f_3" OK
console.log(f1.tellSecret()) // "the secret of f_One is f_3" (not OK for me)

我看到了 solution

this would mean duplicating the function on every instance, and the function lives on the instance, not on the prototype.



另一位作者说 the same solution

That's still not quite traditional classly Javascript, which would define the methods only once on Account.prototype.



那么,有没有解决方案
  • 每个实例都可以有 secret 的唯一值
  • secret仅可用于构造函数中定义的方法
  • 函数不会为每个实例复制

  • ?

    最佳答案

    问题是每次调用构造函数时您都在替换原型(prototype)函数。

    使用旧式的基于闭包的隐私,您不能从原型(prototype)方法访问“私有(private)”成员,因为只有在构造函数中定义的关闭它们的函数才能使用它们。所以你最终会为每个实例重新创建函数(这并不像听起来那么糟糕,但也不是很好)。

    function Example(name) {
    this.name = name;
    var secret = name; // Using `var` here on the basis this is ES5-level code

    // This can't be a prototype function
    this.tellSecret = function() {
    return "the secret of " + this.name + " is " + secret;
    };
    }

    两种选择:

    1) 使用像 Babel 这样的转译器, class语法和私有(private)字段(可能在 ES2021 中,现在通过转译使用了相当长的时间):
    class Example {
    #secret;

    constructor(name) {
    this.name = name;
    this.#secret = name;
    }

    tellSecret() {
    return "the secret of " + this.name + " is " + this.#secret;
    }
    }

    const f1 = new Example("f_One");
    const f3 = new Example("f_3");

    console.log(f3.tellSecret()) // "the secret of f_3 is f_3"
    console.log(f1.tellSecret()) // "the secret of f_One is f_One"

    2) 使用 WeakMap (ES2015+) 包含 secret 信息
    const secrets = new WeakMap();
    class Example {
    constructor(name) {
    this.name = name;
    secrets.set(this, name);
    }

    tellSecret() {
    return "the secret of " + this.name + " is " + secrets.get(this);
    }
    }

    const f1 = new Example("f_One");
    const f3 = new Example("f_3");

    console.log(f3.tellSecret()) // "the secret of f_3 is f_3"
    console.log(f1.tellSecret()) // "the secret of f_One is f_One"

    你把 secrets只有 Example可以访问它。

    您可以使用 WeakMap不使用 class语法也是如此,但如果您正在创建带有关联原型(prototype)的构造函数, classfunction Example 简单并分配给 Example.prototype 上的属性.

    关于javascript:我可以使用原型(prototype)定义一个 "private"变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62347045/

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