JavaScript 覆盖方法 [英] JavaScript override methods

查看:29
本文介绍了JavaScript 覆盖方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有以下代码:

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 中实现这样的功能?

Now the question is, if there is any way in which I can override the method modify from C with the methods that are in A and B. In Java you would use the super-keyword, but how can you achieve something like this in JavaScript?

推荐答案

距离最初的答案已经写了六年了,很多都变了!

It's now six years since the original answer was written and a lot has changed!

  • 如果您使用的是较新版本的 JavaScript,可能是使用 Babel 之类的工具编译的,您可以使用真实的类.
  • 如果您使用由 AngularReact,您需要查看该框架的文档.
  • 如果您使用 ES5 并使用原型手工制作假"类,那么下面的答案仍然和以前一样正确.
  • If you're using a newer version of JavaScript, possibly compiled with a tool like Babel, you can use real classes.
  • If you're using the class-like component constructors provided by Angular or React, you'll want to look in the docs for that framework.
  • If you're using ES5 and making "fake" classes by hand using prototypes, the answer below is still as right as it ever was.

祝你好运!

JavaScript 继承看起来与 Java 有点不同.以下是原生 JavaScript 对象系统的外观:

JavaScript inheritance looks a bit different from Java. Here is how the native JavaScript object system looks:

// 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"

不幸的是,这有点难看,它没有包含一个很好的超级"方法:您必须手动指定要调用的父类的方法.因此,有多种工具可以更好地创建类.尝试查看 Prototype.js、Backbone.js 或包含在 js 中执行 OOP 的更好语法的类似库.

Unfortunately this is a bit ugly and it does not include a very nice way to "super": you have to manually specify which parent classes' method you want to call. As a result, there are a variety of tools to make creating classes nicer. Try looking at Prototype.js, Backbone.js, or a similar library that includes a nicer syntax for doing OOP in js.

这篇关于JavaScript 覆盖方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆