覆盖原型继承方法

覆盖原型继承方法

本文介绍了覆盖原型继承方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这种克隆方法,从中进行原型继承与基本相同。 (唯一的区别是Crockford添加了调用括号,但是由于F是空的,我不知道它是否重要,我不认为这个问题。)

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'

如果我将引用更改为 this.width )等在Viewport到 Viewport.width()等等错误消失,但后来我认为继承不起作用。当我使用任一对象的方法时,会发生错误。我失踪了什么有更好的模式吗?如何做这个工作?

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?

推荐答案

与原型你必须做的事情有点不同:

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...

这篇关于覆盖原型继承方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:54