不能设置未定义的属性'X'。

时间:2022-08-24 13:17:03

I am trying to extract some functionality of a popular open source project, so I can use it as a utility. The functionality is in a particular file, and by the looks it should run standalone (aka $ node filename.js on command line). But it produces an error.

我正在尝试提取一个流行的开源项目的一些功能,所以我可以将它作为一个实用工具使用。该功能在一个特定的文件中,并且看起来它应该独立运行(也就是$ node文件名)。js命令行)。但它会产生一个错误。

After examining the file, I isolated the syntax that produces the error and created a minimal example:

在检查了文件之后,我隔离了产生错误的语法,并创建了一个最小的示例:

File <path>\lib.js:

文件 <路径> \ lib.js:

var Lib;

(function() {

    function X() {};
    X.prototype = {
        foo: function() { console.log('foo'); },
        bar: function() { console.log('bar'); }
    };

    Lib.X = X;

    Lib.Method = function(message) {
        this.x = new X();
        console.log(message);
    }
})();

Lib.Method('foobar');

When this is run on command line:

当这在命令行运行时:

<path>$ node lib.js

Node.js produces following error:

节点。js生成以下错误:

<path>\lib.js:11
        Lib.X = X;
       ^
TypeError: Cannot set property 'X' of undefined
    at <path>\lib.js:11:8
    at Object.<anonymous> (<path>\lib.js:
16:2)
    at Module._compile (module.js:446:26)
    at Object..js (module.js:464:10)
    at Module.load (module.js:353:31)
    at Function._load (module.js:311:12)
    at Array.0 (module.js:484:10)
    at EventEmitter._tickCallback (node.js:190:38)

I can see that the problem is in the statement Lib.X = X;. But I am not sure if that line breaks any syntax/semantic rules. I understand this line as: assign function X to property X of variable Lib.

我可以看出问题在陈述里。但我不确定这行是否违反了任何语法/语义规则。我理解这一行:将函数X赋给变量Lib的属性X。

What am I doing wrong?

我做错了什么?

2 个解决方案

#1


4  

Lib is undefined. undefined is not an object, therefore you can't set any properties on it. You probably want this at the start of the file:

*是未定义的。未定义的不是一个对象,因此您不能在其上设置任何属性。您可能希望在文件开始时这样:

var Lib = {};

#2


3  

Variable Lib is undefined, so you can't assign anything to it.

变量Lib没有定义,所以不能给它赋值。

You need to define it first, as a minimal example:

你需要首先定义它,作为一个最小的例子:

var Lib = {};

#1


4  

Lib is undefined. undefined is not an object, therefore you can't set any properties on it. You probably want this at the start of the file:

*是未定义的。未定义的不是一个对象,因此您不能在其上设置任何属性。您可能希望在文件开始时这样:

var Lib = {};

#2


3  

Variable Lib is undefined, so you can't assign anything to it.

变量Lib没有定义,所以不能给它赋值。

You need to define it first, as a minimal example:

你需要首先定义它,作为一个最小的例子:

var Lib = {};