使用原型继承覆盖方法

时间:2012-01-26 17:31:27

标签: javascript oop design-patterns inheritance prototypal-inheritance

我正在使用此克隆方法进行Pro JavaScript Design Patterns的原型继承,这与Crockford's object() function基本相同。 (唯一的区别是Crockford添加了调用parens,但由于F是空的,我不确定它是否重要。我不认为这个问题。)

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

所以,应用这个,我正在寻找两个对象,一个从另一个继承方法。一个用于视口尺寸,一个用于设备尺寸。但是两者都使用类似的数学比较,所以我认为让一个继承另一个是有意义的。 (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; 
};

但问题是我得到这样的错误:

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

如果我将视口中this.width()等的引用更改为Viewport.width()等,则错误消失但我认为继承不起作用。当我使用来自任一对象的方法时,会发生错误。我错过了什么?这有更好的模式吗?我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

使用原型你必须做一些不同的事情:

var Viewport = {};
Viewport.prototype.inOrOut = function(){...};
Viewport.prototype.width= function(){...};
Viewport.prototype.height = function(){...};
通过这种方式,您将能够正确地继承...

相关问题