1

我有一个 JavaScript 类,我想让它不能被子类化。(类似于在 Java 中使用“final”关键字标记类。)这是我的 JavaScript 类:

function Car(make, model) {
     this.getMake = function( ) { return make; }
     this.getModel = function( ) { return model; }
}
4

3 回答 3

7

JavaScript 面向对象范式是基于原型的,这意味着对象从其他对象“继承”,将它们用作它们的原型。

没有类,Car是一个构造函数,并且该语言允许您扩展几乎任何对象。

如果你可以创建一个Car对象实例,就没有办法阻止这个对象被用作其他构造函数的原型。

于 2009-10-10T19:29:02.450 回答
1

鉴于 JavaScript 甚至实际上没有类(它是基于原型的对象系统,而不是基于类的对象系统),并且它是一种动态语言 [1],您想要做的事情是不可能的。此外,JavaScript 实际上没有继承/子类化——它必须通过复制和扩展对象来伪造。没有办法(据我所知)阻止其他代码这样做。

  1. 在具有元类支持的动态语言中,可以实现这样的功能。JavaScript 不是这样的语言。
于 2009-10-10T19:23:14.113 回答
0

Nope you can't do this directly and don't know that there is a way to do this given Javascript's prototypical inheritance but take a look at Extjs, which is a js framework which has a heavy object oriented type design. Look at the api and more so the source code and you might get closer to where you want to go -- but not totally :)

于 2009-10-10T20:22:55.337 回答