Override Methods with Prototypal Inheritance

2019-02-26 17:34发布

I'm using this clone method for prototypal inheritance from Pro JavaScript Design Patterns which is basically the same as Crockford's object() function. (The only difference is that Crockford adds invoke parens, but since F is empty I'm not sure that it matters. I don't think that the issue.)

clone = function(object) {
    function F() {}
    F.prototype = object;
    return new F;
};

So, applying this, I'm looking to make two objects, one which inherits methods from the other. One is for viewport dimensions and one is for device dimensions. But both use similar math comparisons so I think it makes sense to have one inherit the other. (More info about the actual methods is here.)

var Viewport = {
    inORout: function (curr, min, max) {
        // !@return boolean true if curr equals min or max, or is in between.
        min = min || 0; // Default min.
        return !max ? ( curr >= min ) : ( curr >= min && curr <= max );
    }
  , width: function() {
        return document.documentElement.clientWidth; 
    }
  , height: function() { 
        return document.documentElement.clientHeight; 
    }
  , inWidthRange: function (min, max) {
        return this.inORout(this.width(), min, max);
    }
  , inHeightRange: function (min, max) {
        return this.inORout(this.height(), min, max);
    }
};

// I want to use prototypal inheritance to make Device inherit the
// inORout/inWidthRange/inHeightRange methods from Viewport but 
// override the width() and height() methods:
var Device = clone(Viewport);
Device.width = function() {
    return window.screen.width; 
};
Device.height = function() {
    return window.screen.height; 
};

But the problem is that I get errors like this:

 Object # <Object> has no method 'inORout'
 and 
 Object # <Object> has no method 'width'
 and 
 Object # <Object> has no method 'height'

If I change reference to this.width() etc. in Viewport to Viewport.width() etc. the errors go away but then I think that the inheritance doesn't work. The errors happen when I use methods from either object. What am I missing? Is there a better pattern for this? How can I make this work?

1条回答
smile是对你的礼貌
2楼-- · 2019-02-26 17:45

with prototype you have to do things a little different:

var Viewport = {};
Viewport.prototype.inOrOut = function(){...};
Viewport.prototype.width= function(){...};
Viewport.prototype.height = function(){...};

this way, you will be able to inherit properly...

查看更多
登录 后发表回答