【问题标题】:Overwriting Javascript method outside class, with default behavior使用默认行为覆盖类外的 Javascript 方法
【发布时间】:2012-08-29 09:47:05
【问题描述】:

我正在尝试理解 Javascript OOP。我正在尝试覆盖类中的方法。当“点击”时,该类具有默认功能。我想覆盖那个函数,所以当点击时会发生一些新的事情。

我有一个如下所示的 Javascript 类:

AlertModal = function(){
  var x = *this is my close object;

  x.onclick = destoryAlert;

  function destroyAlert(){
    console.log('destroy');
  }
}

我的 HTML 文件显示:

<script type="text/javascript">
  window.alert = function (message) {
    var newAlert = new AlertModal();
    newAlert.destroyAlert = function(){
      console.log('new alert destroy');
    };

    newAlert.destroyAlert();
  };

我收到“新警报销毁”,这很棒。但是当我单击“x”时,它也表示销毁。所以它被覆盖了,但不是?!就像它在调用时创建了一个新的“destroyAlert”函数,但保留了默认值。

谁能告诉我如何做到这一点,创建一个具有默认功能的类,但如果需要如何覆盖它?

我习惯于使用 Java 和 Actionscript 进行编程、扩展类和覆盖公共/受保护的方法,但这样做 Javascript 似乎有很大不同,我无法理解这样做的逻辑。

谢谢,

【问题讨论】:

    标签: javascript class overriding overwrite


    【解决方案1】:
    x.onclick = destroyAlertl
    

    将 x 的 onclick 处理程序设置为引用本地函数

    newAlert.destroyAlert = ...
    

    将此对象的destroyAlert 属性集设置为不同的函数。它不会更改存储在x.onclick 中的引用。

    需要在AlertModalprototype上加上“默认”功能:

    AlertModal.prototype.destroyAlert = function() {
         ...
    }
    

    并以不同的方式注册处理程序:

    var self = this;
    x.onclick = function() {
        self.destroyAlert();
    }
    

    如果您随后覆盖此类对象的destroyAlert 属性,则将改为调用新函数。

    【讨论】:

    • 既然它没有改变引用,而且我创建了另一个像 destroyAlert1 这样的引用,那不是仍然调用默认值,并且新创建的?我的目标是覆盖现有函数。
    • Alnitak: x.onclick = function() { this.destroyAlert(); } 不正确。因为this 将引用x。他需要使用闭包。
    • Alexey:闭包是什么意思?
    【解决方案2】:

    您可以覆盖实例级别的方法:

    AlertModal = function() {
        this.init();
    };
    
    AlertModal.prototype.init = function() {
        var modal = this;
        var x = ...;
        x.onclick = function() {
            // Note that I'm not using `this` here, because it would
            // reference `x` instead of the modal. But we can pass the modal
            // from the outer scope. This is called a lexical closure.
            modal.destroy();
        };
    };
    
    AlertModal.prototype.destroy = function() {
        console.log('destroy');
    };
    
    var myalert = new AlertModal();
    myalert.destroy = function() {
        console.log('new destroy');
    };
    
    myalert.destroy();
    

    但如果您想在多个地方执行相同的覆盖,最好通过从 AlertModal 类继承来创建专门的 OtherAlertModal。这是 JavaScript 中继承的好方法:http://ejohn.org/blog/simple-javascript-inheritance/

    【讨论】:

    • 这正是我所需要的!谢谢@Alexey。我以前从未使用过原型(再次来自 AS3),但我现在会阅读它,再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多