zoukankan      html  css  js  c++  java
  • 如何在JavaScript的实例对象中改写原型方法

      在JavaScript中,我们通常可以像下面的代码这样来简单地定义一个类:

    var sample = function() {
        // constructor code here 
    }
    
    sample.prototype.func1 = function() {
        // func1 code here
    }
    
    sample.prototype.func2 = function() {
        // func2 code here
    }
    
    /* more sample prototype functions here... */

      然后使用下面的代码来实例化,并访问其中的原型方法:

    var sampleInstance = new sample();
    sampleInstance.func1();
    sampleInstance.func2();
    // call more sample object prototype functions

      但是如果我们想改写其中一个原型方法,并且不破坏原有的sample对象,如何来实现呢?一个最简单的方法就是再构建一个类,使其继承sample,然后在继承类的原型方法中改写基类的方法,就像下面这样:

    var subSample = function() {
        // constructor code here
    }
    
    // inherit from sample
    subSample.prototype = new sample();
    subSample.prototype.fun1 = function() {
        // overwrite the sample's func1
    }

      但是如果没有构建继承类,而想改写原型方法,可以直接使用下面的代码:

    var sampleInstance = new sample();
    sampleInstance.func1 = function() {
        sample.prototype.fun1.call(this); // call sample's func1
        // sampleInstance.func1 code here
    }

      我们重新定义了sample的实例对象的func1方法,并在其中访问了其原型方法func1,然后又在其中添加了一些额外代码。通过这样的方法,我们对sample的原型方法进行了扩展,并且没有创建派生类,而且也没有破坏sample的原型方法。

  • 相关阅读:
    DataTable.Compute方法使用实例
    asp.net GridView实现多表头类 多行表头实现方法
    VS2010保存时控件验证(用onclientclick事件) js脚本
    asp.net网页中添加年月日时分秒星期。
    Hbase写入hdfs源码分析
    Hbase的WAL在RegionServer基本调用过程
    Redis设计思路学习与总结
    腾讯云TDSQL审计原理揭秘
    Hbase WAL线程模型源码分析
    在腾讯云上创建您的SQL Cluster(4)
  • 原文地址:https://www.cnblogs.com/jaxu/p/15382725.html
Copyright © 2011-2022 走看看