Javascript 意外标记'';在向原型添加功能时

Javascript 意外标记'';在向原型添加功能时,javascript,Javascript,我试图创建一个纯虚拟基类的javascript等价物。但我得到了一个语法错误,“意外标记”。语法有什么问题 MyNamespace.MySubNamespace.Repository = { Repository.prototype.Get = function(id) { // <-- error occurs here } Repository.prototype.GetAll = function() { } Repository.pr

我试图创建一个纯虚拟基类的javascript等价物。但我得到了一个语法错误,“意外标记”。语法有什么问题

MyNamespace.MySubNamespace.Repository = {
    Repository.prototype.Get = function(id) { // <-- error occurs here

    }

    Repository.prototype.GetAll = function() {

    }

    Repository.prototype.Add = function(entity) {

    }

    Repository.prototype.AddRange = function(entities) {

    }

    Repository.prototype.Remove = function(entity) {

    }

    Repository.prototype.RemoveRange = function(entities) {

    }
}
MyNamespace.MySubNamespace.Repository={

Repository.prototype.Get=function(id){/
prototype
属性用于函数,
Repository
是一个对象,它没有
prototype
属性。

您的代码需要一个对象,但您将该对象视为一个方法

MyNamespace.MySubNamespace.Repository = {   <-- Object start
    Repository.prototype.Get = function(id) { // <-- You are setting a method...

嗯,您需要定义该名称空间的每个级别,然后您需要理解,您要设置的存储库不是一个类之类的代码块,而是一个对象文本,因此必须使用适当的语法

var MyNamespace = {MySubNamespace: {}};

MyNamespace.MySubNamespace.Repository = { // This is not a block. This is an object literal.
    Get: function(id) {

    },

    GetAll: function() {

    },

    Add: function(entity) {

    },

    AddRange: function(entities) {

    },

    Remove: function(entity) {

    },

    RemoveRange: function(entities) {

    }
};

对Javascript子类化代码的良好理解是无效的…你有一个对象,你在其中设置代码…名称空间定义正确,为了清晰起见,我只是将其从文章中排除。但这不是使用原型继承。方法将针对每个实例重新定义。我只是更正OP提供的代码。我不是在评论op应该怎么做,因为现在还不完全清楚他在做什么。他可能会在以后将一个对象设置为函数的原型对象。这样做会将原始错误替换为:“未捕获的TypeError:无法设置未定义的属性‘prototype’”我想您可能还想进一步了解如何构造对象继承,因为“名称空间”嵌套对象似乎不是一组函数。@好吧,您需要先设置
存储库
。我已经更新了问题,以包含名称空间构造。
MyNamespace.MySubNamespace.Repository = function() { };
MyNamespace.MySubNamespace.Repository.prototype = {
    get : function(){},
    add : function(){}
};
var MyNamespace = {MySubNamespace: {}};

MyNamespace.MySubNamespace.Repository = { // This is not a block. This is an object literal.
    Get: function(id) {

    },

    GetAll: function() {

    },

    Add: function(entity) {

    },

    AddRange: function(entities) {

    },

    Remove: function(entity) {

    },

    RemoveRange: function(entities) {

    }
};