javascript - 如何在不使用 "new"运算符的情况下使用原型(prototype)继承

标签 javascript closures prototype

所以我尝试使用闭包创建具有原型(prototype)继承的对象,而无需使用“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

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

我感谢所有的帮助。

最佳答案

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

最好使用示例:-

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

关于javascript - 如何在不使用 "new"运算符的情况下使用原型(prototype)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12554443/

相关文章:

javascript - 如何使用 ROUND HALF UP 四舍五入。我们大多数人在小学时被教授的舍入模式

java - 通过 AngularJS 上传文件后从 Spring Controller 返回 Json

collections - groovy:更改列表的每个元素并加入

javascript - __proto__ 和 JavaScript 中的继承

groovy - 如何将 Groovy 闭包变量注入(inject) Spock 模拟谓词参数?

循环内的 JavaScript 闭包 – 简单的实际示例

javascript - 从子对象函数访问原型(prototype)

javascript - 加载外部网站 View jQuery ajax

javascript - Try/catch oneliner 可用吗?

javascript - 如何将自定义组件添加到 createMaterialTopTabNavigator 选项卡栏