gpt4 book ai didi

javascript - 用一个例子描述 Revealing Module Pattern 经常被引用的缺点

转载 作者:搜寻专家 更新时间:2023-11-01 04:35:05 25 4
gpt4 key购买 nike

我阅读了 Javascript 设计模式,然后阅读了关于 RMP 的一系列 SO 答案,并且我一直发现在提到缺点的地方,它是书中的直接引用:

A disadvantage of this pattern is that if a private function refers to a public function, that public function can’t be overridden if a patch is necessary. This is because the private function will continue to refer to the private implementation, and the pattern doesn’t apply to public members, only to functions.

Public object members that refer to private variables are also subject to the no-patch rule.

As a result of this, modules created with the Revealing Module pattern may be more fragile than those created with the original Module pattern, so care should be taken during usage.

抱歉,我很愚蠢,但上面的解释并不适合我。有人可以提供一个代码丰富的可视化示例来说明该劣势意味着什么吗?

最佳答案

我认为这解释了经常被引用的劣势。就个人而言,如果您更喜欢组合而不是继承,我认为这没什么大不了的,因为它根本不会出现。

var revealed = (function() {      
function foo() {
return baz();
}

function bar() {
return "I am the original bar!";
}

// private function always calls bar because it's in the closure
// and it can't see the "instance" variable
function baz() {
return bar();
}

return { foo : foo, bar : bar }
})();

var child = Object.create(revealed);

child.bar = function() {
return "I am the new bar!";
}

// we want this to call the new bar but it doesn't
console.log(child.foo()); // I am the original bar!

希望这对您有所帮助!

关于javascript - 用一个例子描述 Revealing Module Pattern 经常被引用的缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47042523/

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