|
导读微信小程序,简称小程序,英文名Mini Program,是一种不需要下载安装即可使用的应用,它实现了应用“触手可及”的梦想,用户扫一扫或搜一下即可打开应用。小程序是一种不用下载就能使用的应用,也是一... 微信小程序,简称小程序,英文名Mini Program,是一种不需要下载安装即可使用的应用,它实现了应用“触手可及”的梦想,用户扫一扫或搜一下即可打开应用。小程序是一种不用下载就能使用的应用,也是一项门槛非常高的创新,经过将近两年的发展,已经构造了新的小程序开发环境和开发者生态。 微信小程序中module.exports与exports的用法可以查看下面官方提供的文档,使用起来还是比较简单方便的,但时对于这两者的区别解释的不是很明白。
为了更好的理解 exports 和module.exports 的关系,我们先来补点 js 基础。示例: // index.js
Page({
onLoad: function(){
var a = {name: '张三'};
var b = a;
console.log(a);
console.log(b);
b.name = '李四';
console.log(a);
console.log(b);
var b = {name: '王五'};
console.log(a);
console.log(b);
}
})运行 app.js 结果为: { name: '张三' }
{ name: '张三' }
{ name: '李四' }
{ name: '李四' }
{ name: '李四' }
{ name: '王五' }解释一下: 明白了上述例子后,我们进入正题。我们只需知道三点即可知道exports 和module.exports 的区别了:
下面就在微信小程序中module.exports和exports的区别做出示例 // common.js
function sayHello(name) {
console.log(`Hello ${name} !`);
}
function sayGoodbye(name) {
console.log(`Goodbye ${name} !`);
}
// 第一种情况,module.exports初始值为空对象,两个函数使用module.exports或exports都一样效果
module.exports.sayHello = sayHello;
module.exports.sayGoodbye = sayGoodbye;
exports.sayHello = sayHello;
exports.sayGoodbye = sayGoodbye;
// 第二种情况,module.exports初始值不为空对象,只能使用module.exports暴露接口,而不能使用exports暴露,会出现is not a function错误。
module.exports = {name:1};// module.exports给一个初始值
//以下两个正常使用
module.exports.sayHello = sayHello;
module.exports.sayGoodbye = sayGoodbye;
//使用以下两个会报错误sayHello is not a function
exports.sayHello = sayHello;
exports.sayGoodbye = sayGoodbye;综上所述,当module.exports 指向新的对象时,exports 断开了与 module.exports 的引用,module.exports 指向了新的内存块,而 exports 还是指向原来的内存块。 以上就是微信小程序中module.exports和exports的区别的详细内容,更多请关注php中文网其它相关文章! 小程序是一种不需要下载安装即可使用的应用,它实现了应用“触手可及”的梦想,用户扫一扫或者搜一下即可打开应用。 |
温馨提示:喜欢本站的话,请收藏一下本站!