团队开发中,遵循一定的代码规范,有利于提升团队开发效率和方便后期维护。常见的代码规范 例如 airbnb规范等等。下边是一些开发我开发中尽量遵守的规范。
- 变量的声明,尽量用
let
或 const
,而不是使用var
- 当我们声明一个对象的时候,尽量用对象字面量的方式来声明;
const obj = {}
const arr = []
const obj = {
// 简写
fn1(){
console.log('fn1')
},
// 非简写
fn2:function(){
console.log('fn2')
}
}
- 对象属性名和属性值的变量相同的情况下,尽量用简写,而且尽量把简写属性写在对象其他属性的最上边;最后一个属性后边尽量跟一个逗号
const userName = 'john'
const person = {
// 相当于 userName:userName
userName,
// 最后一个属性后边尽量跟一个逗号
age:20,
}
// 例如我们在调用云函数的时候,如果我们直接用普通的函数模式作为then的回调。那么这个时候会报错。`cannot read property setData of undefined`。因为此时this指向不对
wx.cloud.callFunction({
name:'login'
}).then(function(res){
console.log(res)
this.setData({
openid:res.result.openid
})
})
// 除非我们先获取到this。以前通常的做法是
const that= this
wx.cloud.callFunction({
name:'login'
}).then(function(res){
console.log(res)
that.setData({
openid:res.result.openid
})
})
// 现在我们直接用箭头函数会方便很多
wx.cloud.callFunction({
name:'login'
}).then((res) => {
console.log(res)
that.setData({
openid:res.result.openid
})
})
当然还有更多的规范可以应用,在这里就不做举例了。以后有时间可以慢慢增加