闭包测试
作者:互联网
(function() {
// -- 基础数据类型
{
function func (val = 0) {
return {
decrease() {
val--
},
increase() {
val++
},
getVal() {
return val
}
}
}
const props = 0
const instance1 = func(props)
const instance2 = func(props)
console.log(instance1.getVal()) // 0
console.log(instance2.getVal()) // 0
console.log(props) // 0
instance1.increase()
console.log(instance1.getVal()) // 1
console.log(instance2.getVal()) // 0
console.log(props) // 0
}
// -- 引用数据类型 { console.log('-- -- --') function func (param = { val: 0 }) { return { decrease() { param.val-- }, increase() { param.val++ }, getVal() { return param.val } } } const props = { val: 0 } const instance1 = func(props) const instance2 = func(props) console.log(instance1.getVal()) // 0 console.log(instance2.getVal()) // 0 console.log(props.val) // 0 instance1.increase() console.log(instance1.getVal()) // 1 console.log(instance2.getVal()) // 1 console.log(props.val) // 1 } }())
// -- 引用数据类型 { console.log('-- -- --') function func (param = { val: 0 }) { return { decrease() { param.val-- }, increase() { param.val++ }, getVal() { return param.val } } } const props = { val: 0 } const instance1 = func(props) const instance2 = func(props) console.log(instance1.getVal()) // 0 console.log(instance2.getVal()) // 0 console.log(props.val) // 0 instance1.increase() console.log(instance1.getVal()) // 1 console.log(instance2.getVal()) // 1 console.log(props.val) // 1 } }())
标签:闭包,console,log,val,getVal,instance1,测试,props 来源: https://www.cnblogs.com/hello-world-01/p/16649465.html