【问题标题】:Override Methods with Prototypal Inheritance使用原型继承覆盖方法
【发布时间】:2012-01-26 17:31:27
【问题描述】:

我正在使用这种克隆方法从Pro JavaScript Design Patterns 进行原型继承,这与Crockford's object() function 基本相同。 (唯一的区别是 Crockford 添加了调用括号,但由于 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() 等,错误就会消失,但我认为继承不起作用。当我使用来自任一对象的方法时,就会发生错误。我错过了什么?有没有更好的模式呢?我怎样才能做到这一点?

【问题讨论】:

  • @Raynos @André Alçada Padez 我想通了。问题是我使用这些方法的方式改变了this 的上下文。方法未在 that this. 上定义

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


【解决方案1】:

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

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

这样,你就可以正常继承了……

【讨论】:

  • 这不是经典继承吗?无论如何我都试过了,它给出了错误Cannot set property 'inORout' of undefinedclone() 方法应该处理这个问题。我相信它相当于在 JavaScript 1.8.5 中添加的Object.create developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
  • function F() {} -> 你不是少了一个 =(等号)吗?
  • 函数内部function F() {}等价于var F = function() {};
  • @AndréAlçadaPadez function F() {} 只是一个局部函数声明。其工作方式与全局函数声明完全相同,只是它们是本地的。
  • 我知道这不是一个答案,但我试过你的答案,它有效jsfiddle.net/andrepadez/c7GYy
猜你喜欢
  • 1970-01-01
  • 2013-08-15
  • 2012-11-20
  • 1970-01-01
  • 2013-01-11
  • 2016-06-04
  • 2016-01-25
  • 2011-06-14
相关资源
最近更新 更多