我刚接触node.js(以及stackoverflow),没有找到确切的解释。
这可能只是一份试探性答案,但希望它能帮助其他正在从Python/其他面向对象框架过渡的人。
我看过其他关于js中原型概念的文章,还有一些解释node.js的module.exports。
我正在研究Ghost CMS,他们两者都在使用。我似乎无法分辨在某些情况下为什么要选择其中之一。
任何帮助都将不胜感激,即使只是指向其他链接。
我刚接触node.js(以及stackoverflow),没有找到确切的解释。
这可能只是一份试探性答案,但希望它能帮助其他正在从Python/其他面向对象框架过渡的人。
我看过其他关于js中原型概念的文章,还有一些解释node.js的module.exports。
我正在研究Ghost CMS,他们两者都在使用。我似乎无法分辨在某些情况下为什么要选择其中之一。
任何帮助都将不胜感激,即使只是指向其他链接。
实际上它们在某种程度上是可以互换的:
使用prototype
:
//module.js
function Person (name) {
this.name = name;
}
Person.prototype.sayName = function () {
console.log(this.name);
}
module.exports = Person;
//index.js
var Person = require('./module.js');
var person = new Person('John');
person.sayName();
使用 exports
:
//module.js
exports.init = function (name) {
this.name = name;
return this;
}
exports.sayName = function () {
console.log(this.name);
}
//index.js
var Person = require('./module.js');
var person = Object.create(Person).init('John');
person.sayName();
使用Node.js时,module.exports是公开模块接口的方法。
/* my-module.js */
exports.coolFunction = function(callback) {
// stuff & things
callback(whatever);
};
在导入/要求它之后,另一个模块可以消费此接口:
/* another-module.js */
var myModule = require('my-module');
myModule.coolFunction(function(error) { ... });
原型(JavaScript 中的一个普通特性),则可用于定义从构造函数实例化出来的对象所共享的属性和方法。
function User() {
this.name = null;
}
User.prototype.printGreeting = function() {
console.log('Hello. My name is: ' + this.name);
};
var user = new User();
user.name = 'Jill';
user.printGreeting();
干杯。
module.exports
用于导入其他模块;原型是用于创建实例的。 - SLaks