As I delve into understanding reactivity in Vue, the concept of how reactivity is achieved when passing a value as a function parameter perplexes me.
//here is the actual code snippet
var obj = {a: 'aa'}
function reactive(obj, key, value) {
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get() {
return value
},
set(val) {
value = val
}
})
}
function observe(obj) {
Object.keys(obj).map((key, index) => {
reactive(obj, key, obj[key])
})
}
observe(obj)
obj.a //'aa'
obj.a ='bb' //'bb'
//here is the error-inducing code snippet
var obj = {a: 'aa'}
function reactive(obj, key) {
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get() {
return obj[key]
},
set(val) {
obj[key] = val
}
})
}
function observe(obj) {
Object.keys(obj).map((key, index) => {
reactive(obj, key)
})
}
observe(obj)
obj.a //VM1649:6 Uncaught RangeError: Maximum call stack size exceeded
When attempting to set the value using 'obj[key]', it results in a RangeError
//this is an illustrative example
var obj = {a: 'aa'}
function reactive(obj, key, value) {
value = 'bb'
}
function observe(obj) {
Object.keys(obj).map((key, index) => {
reactive(obj, key, obj[key])
})
}
observe(obj)
obj.a //'aa'
Nevertheless, the example emphasized that modifying the object's value through assignment is not possible within this context