从模块外部访问内部成员

从模块外部访问内部成员

1.使用exports

exports.js:

var myMsg='hello';
var funcname = function () {
    return 'testMsg';
};

exports.msg = myMsg;
exports.funcname = funcname;

foo.js:

var foo = require('./exports.js');

console.log(foo.msg);

console.log(foo.funcname());

2.将模块定义为类(module.exports)

student.js:

var _name,_age;
var name = '',age =0;
//模块对象的构造函数
var foo=function (name,age) {
    _name = name;
    _age= age;
}

foo.prototype.GetName= function () {
    return _name;
}

foo.prototype.SetName= function (name) {
    _name= name;
}
foo.prototype.GetAge= function () {
    return _age;
}

foo.prototype.SetAge= function (age) {
    _age= age;
}

foo.prototype.name = name;
foo.prototype.age = age;
module.exports = foo;

stuTest.js

var foo = require('./student.js');
var myFoo = new foo("tom",14);
console.log("获取修改前的私有变量");
console.log(myFoo.GetName());
console.log(myFoo.GetAge());

myFoo.SetName("bob");
myFoo.SetAge(20);
console.log("获取修改后的私有变量");
console.log(myFoo.GetName());
console.log(myFoo.GetAge());
上一篇:微服务系统中的数据一致性,你都会了吗


下一篇:mybatis开启二级缓存小记