如何重写Javascript类中的函数并调用基本函数

时间:2018-09-21 10:34:34

标签: javascript

是否可以重写Javascript类中的函数,并将其称为基本实现?我已经通过使用原型实现了这一目标,但是我试图为某些数据保留隐私。

这是我到目前为止的内容,并且不起作用。我知道为什么它不起作用,但是我看不出解决它的方法。我开始怀疑这是否可以在javascript中实现(无需花费很多精力)。

此外,我需要支持IE11,因此不能使用ES6。

    var NoProto = NoProto || {};

    NoProto.Shape = (function(){
        var thing = function(name){
            var privateData = 'this is a ' + name;

            var self = this;
            this.base = function(){
                return self;
            };

            this.doStuff = function(){
                return privateData;
            };
        };

        return thing;
    })();

    NoProto.Square = (function(){
        var thing = function(colour){
            NoProto.Shape.call(this, "square");

            this.doStuff = function(){
                // this fails (stack overflow)
                // ------> how to call the "base" function: doStuff, and preserve the private data?
                var val = this.base().doStuff();
                return val + ', which is '+ colour;
            };
        };

        thing.prototype = Object.create(NoProto.Shape.prototype);

        return thing;
    })();

用法:

        var noProtoSqr = new NoProto.Square('blue');
        try {
            alert(noProtoSqr.doStuff()); // ---> Stack Overflow!
        } catch (e){
            console.error('There was an error: ' + e);
        }

作为参考,这是我如何将其与原型配合使用的方式:

    var Proto = Proto || {};

    Proto.Shape = (function(){
        var thing = function(name){
            this._pseudoPrivateData = 'this is a ' + name;
        };

        thing.prototype._pseudoPrivateData = '';
        thing.prototype.doStuff = function(){
            return this._pseudoPrivateData;
        };

        return thing;
    })();

    Proto.Square = (function(){
        var thing = function(colour){
            Proto.Shape.call(this, "square");
            this._colour = colour;
        };

        thing.prototype = Object.create(Proto.Shape.prototype);

        thing.prototype._colour = '';
        thing.prototype.doStuff = function(){
            var val = Proto.Shape.prototype.doStuff.call(this);
            return val + ', which is '+ this._colour;
        };

        return thing;
    })();

用法:

        var protoSqr = new Proto.Square('blue');
        try {
            alert(protoSqr.doStuff());  // --> "this is a square, which is blue"
        } catch (e){
            console.error('There was an error: ' + e);
        }

1 个答案:

答案 0 :(得分:1)

使用时

NoProto.Shape.call(this, "square")

这将Shape的{​​{1}}分配给当前实例(如果您要这样做的话)。因此,现在doStuff将引用this.doStuff中原始的doStuff函数。如果要在当前实例上覆盖NoProto.shape函数,同时又能够调用原始doStuff,请在分配给doStuff之前保存对旧doStuff的引用: / p>

this.doStuff

实时摘要:

var thing = function(colour){
  NoProto.Shape.call(this, "square");
  const oldDoStuff = this.doStuff;
  this.doStuff = function(){
    var val = oldDoStuff();
    return val + ', which is '+ colour;
  };
};