gpt4 book ai didi

Javascript 模块 : Prototype vs. 导出

转载 作者:IT老高 更新时间:2023-10-28 23:18:58 25 4
gpt4 key购买 nike

我是 node.js(和 stackoverflow)的新手,还没有找到对此的确切解释。

这可能是一个试用答案,但希望它可以帮助其他也从 Python/其他面向对象框架过渡的人。

我看过其他关于 js 中原型(prototype)概念是什么的文章,以及其他解释 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();

导出:

//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();

不过,第一个示例更适合 javascript。

关于Javascript 模块 : Prototype vs. 导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21939568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com