[英]Difference between javascript class declaration
I was trying to create a module for node.js and i noticed something. 我试图为node.js创建一个模块,我发现了一些东西。 Example
例
function Example() {
this.property = "something";
}
Example.prototype.run = function() {
console.log('hello world')
}
module.exports = Example;
with this code it say's that there's no method run. 用这段代码说它没有方法运行。 I need it to declare like
我需要它来宣布
Example.prototype.run = function run() {}
to work. 上班。 Why is that happening ?
为什么会这样?
This should work fine as long as you actually call the constructor and create an object which is how you've configured the Example code: 只要您实际调用构造函数并创建一个对象,您应该如何配置示例代码,这应该可以正常工作:
var Example = require("./example");
var item = new Example();
item.run();
You need to load the module and instantiate the Example class. 您需要加载模块并实例化 Example类。
Example.js : Example.js:
function Example() {
this.property = "something";
}
Example.prototype.run = function() {
console.log('hello world')
}
module.exports = Example;
main.js : main.js:
var Example = require("./Example.js");
var example = new Example();
example.run();
run: 跑:
$ node main.js
hello world
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.