假设您有以下代码:
function A() {
function modify() {
x = 300;
y = 400;
}
var c = new C();
}
function B() {
function modify(){
x = 3000;
y = 4000;
}
var c = new C();
}
C = function () {
var x = 10;
var y = 20;
function modify() {
x = 30;
y = 40;
};
modify();
alert("The sum is: " + (x+y));
}
现在的问题是,是否有任何方法可以使用 A
中的方法覆盖 C
中的方法 modify
> 和 B
。在 Java 中,您会使用 super
关键字,但如何在 JavaScript 中实现类似的功能呢?
最佳答案
编辑:从最初的答案写到现在已经六年了,发生了很多变化!
- 如果您使用的是较新版本的 JavaScript,可能是使用 Babel 等工具编译的, 你可以 use real classes .
- 如果您正在使用 Angular 提供的类组件构造函数或 React ,您需要查看该框架的文档。
- 如果您正在使用 ES5 并使用原型(prototype)手工制作“假”类,那么下面的答案仍然和以前一样正确。
祝你好运!
JavaScript 继承看起来与 Java 有点不同。以下是 native JavaScript 对象系统的外观:
// Create a class
function Vehicle(color){
this.color = color;
}
// Add an instance method
Vehicle.prototype.go = function(){
return "Underway in " + this.color;
}
// Add a second class
function Car(color){
this.color = color;
}
// And declare it is a subclass of the first
Car.prototype = new Vehicle();
// Override the instance method
Car.prototype.go = function(){
return Vehicle.prototype.go.call(this) + " car"
}
// Create some instances and see the overridden behavior.
var v = new Vehicle("blue");
v.go() // "Underway in blue"
var c = new Car("red");
c.go() // "Underway in red car"
不幸的是,这有点难看,而且它不包含一个很好的“ super ”方法:您必须手动指定要调用哪个父类的方法。因此,有多种工具可以更好地创建类。尝试查看 Prototype.js、Backbone.js 或包含用于在 js 中执行 OOP 的更好语法的类似库。
关于JavaScript 覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6885404/