Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【Node】exports与module.exports区别 #14

Open
dongtong opened this issue May 7, 2016 · 0 comments
Open

【Node】exports与module.exports区别 #14

dongtong opened this issue May 7, 2016 · 0 comments

Comments

@dongtong
Copy link
Owner

dongtong commented May 7, 2016

  • 如果想导出的是一个类型或者抽象的对象,使用module.exports
// user.js
module.exports = function (name, age) {
    this.name = name;
    this.age = age;
    this.greet = function () {
        console.log('I am ' + this.name + ' and I am ' + this.age + 'years old');
    }
}

var User = require('./user');
var user = new User('foobar', 30);
user.greet();

//config.js

exports.version  = '1.0.0';
  • 如果导出的是一个具体的实例,使用exports
  • module.exports是node中真正的模块导出方法,export是module.exports的一个辅助方法。最后返回給调用者的是module.exports而不是exports
  • 如果在一个模块中,同时返回module.exports和exports,那么exports实例将被忽略
module.exports = "foobar";
exports.greet = function () {
    console.log('I am not existed')
}
  • 两种方法并不相同,如果想改变引用模块内部状态,使用module.exports, 否则推荐使用exports
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant