【问题标题】:How to use prototype inheritance without the "new" operator如何在没有“new”运算符的情况下使用原型继承
【发布时间】:2012-09-23 17:17:38
【问题描述】:

所以我试图在没有使用闭包的“new”运算符的情况下制作具有原型继承的对象。 我的代码是:

var TABLE=function (tableId) {
var table=(document.getElementById(tableId)||{}),
    colName=[],
    rows,
    cols,
    selectedRow;

//private methods

    var updateRows=function(){
        //Code that updates the number of row of the table
    }
    updateRows();

//Declare the public methods for the object

var methods={
    prototype:{
        cols:function () {
        return cols;
        },
        rows:function () {
            return rows;
        }
    }
};
    return methods;
}

var table=Table("Inventory")
alert(table.rows()) //I get undefined
alert(table.prototype.rows()) //I get the actual number of rows

我做错了什么?你认为我可以为此使用一些更好的编码方式吗

感谢所有帮助。

【问题讨论】:

  • 原型继承显然 new 一起工作,所以省略它然后抱怨是行不通的。 “我想开没有轮胎的车”。太糟糕了..
  • 在这种情况下您想使用“原型”的原因是什么?在我看来,如果您只是删除方法结构中的“原型”键,您的代码会按预期工作吗?基本上你似乎不需要任何形式的继承来做你正在做的事情......
  • 我刚刚阅读了 Douglas Crockford 的 JavaScript:The Good Parts。他实际上建议我们创建对象时避免使用“new”运算符。所以我客人我想这样做,并且有原型继承。我不是 javascript 专家,但我想成为一名专家
  • Douglas Crockford 实际上推荐的是在需要的地方使用浅继承。从我上面看到的你不需要继承......但如果你这样做了,使用'new'并使用 .prototype 到一个简单的级别会好得多。只是添加我自己的个人笔记,我已经编写 javascript 应用程序、插件和脚本大约 13 年了.. 我从来不需要使用 .prototype 来实现我的目标 - 但如果没有“新”,我不会有很多远的。我最接近“继承”的方式是让一个对象实例被许多其他实例静态使用。

标签: javascript closures prototype


【解决方案1】:

如果您想使用原型继承,我们必须使用 new 关键字。

最好的例子:-

http://www.klauskomenda.com/code/javascript-inheritance-by-example/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 2016-03-06
    相关资源
    最近更新 更多