意外的令牌''在向原型添加功能时

Unexpected token '.' when adding function to prototype

本文关键字:原型 添加 功能 令牌 意外      更新时间:2023-09-26

我正在尝试创建一个纯虚拟基类的javascript等价物。但是我得到了一个语法错误,"Unexpected token"。语法有什么问题?

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) {
    }
}

编辑:以下是命名空间的构造方式。

var MyNamespace = MyNamespace || {};
MyNamespace.createNamespace = function (namespace) {
    var nsparts = namespace.split(".");
    var parent = MyNamespace;
    if (nsparts[0] === "MyNamespace") {
        nsparts = nsparts.slice(1);
    }
    for (var i = 0; i < nsparts.length; i++) {
        var partname = nsparts[i];
        if (typeof parent[partname] === "undefined") {
            parent[partname] = {};
        }
        parent = parent[partname];
    }
    return parent;
};
MyNamespace.createNamespace("MyNamespace.MySubNamespace");

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

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

你应该做的是

MyNamespace.MySubNamespace.Repository = function() { };
MyNamespace.MySubNamespace.Repository.prototype = {
    get : function(){},
    add : function(){}
};

prototype属性用于函数,Repository是一个没有prototype属性的对象。

Uhm,您需要定义该名称空间的每个级别,然后您需要理解,您将Repository设置为的不是像类那样的代码块,而是对象文字,因此必须使用适当的语法。

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) {
    }
};