JavaScript 最终方法
javascript中的方法可以是final的吗? 如何避免它被子类覆盖?
Can a method in javascript be final?
How to avoid it to be overriden by a subclass?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从传统意义上讲,不,您不能拥有私有/受保护的方法或阻止它们被覆盖。
然而,您可以做的是将方法封装在一个作用域中,然后简单地不公开它们:
这就是您所能得到的最接近的结果。我不久前写了一篇关于此的文章: http://www.htmlgoodies.com/primers/jsp/article.php/3600451/Javascript-Basics-Part-8.htm
您还可以使用
__defineGetter__
和__defineSetter__
来阻止访问,但这些并不是 100% 跨浏览器。In the traditional sense, no, you can't have private/protected methods or prevent them from being overridden.
What you can do, however, is encapsulate methods in a scope and then simply not expose them:
That's about as close as you can get. I wrote an article on this a while ago: http://www.htmlgoodies.com/primers/jsp/article.php/3600451/Javascript-Basics-Part-8.htm
You can also use
__defineGetter__
and__defineSetter__
to prevent access, but those aren't 100% cross-browser.您可以将 defineProperty 用于成员 您想要确保安全。
Mike 提到了可配置属性,用于防止重新定义 - 删除。我也添加这个。
另一个选项
Object.freeze。但它保护对象中的所有成员。
You can use defineProperty for what member you want to make secure.
Mike has mentioned
configurable
attribute for preventing from redefine -- delete. I'm adding this too.Another option
Object.freeze. But it's secures all members in object.
据我所知,该语言没有办法强制对象属性的最终确定性。你必须强制执行这一点。 “非常确定”的一种方法是使用极不可能在子类中使用的命名约定。像这样的东西
可能会工作得很好。另一种选择是使用 hasOwnProperty() 函数来检测父对象是否已经具有属性,然后再用其他内容覆盖它。
As far as I know, the language does not have a way of enforcing finality of object properties. You have to enforce this on your end. One way to be "pretty sure" is to use a naming convention that is extremely unlikely to be used in a subclass. something like
Would probably work pretty well. Another option is to use the hasOwnProperty() function to detect if a parent object already has a property before overwriting it with something else.