Proxy and defineProterty of es6

es6"s proxy proxy listens to object properties, isn"t that the same as the original defineProterty"s set,get function? what"s the difference between the two

Jul.28,2021

proxy 's set , get is much more powerful, it doesn't need to be predefined to listen.
I answered a question earlier and wrote a simple value function

/**
 * @param target
 * @param exec 
 * @returns {*}
 */
function getter(target, exec = '_') {
  return new Proxy({}, {
    get: (o, n) => {
      return n === exec ?
        target :
        getter(typeof target === 'undefined' ? target : target[n], exec)
    }
  });
}

this is using the method. Calling the object's arbitrary depth property will not report an error

let obj = {
  school: {
    class1: {
      student: 50
    }
  }
};

console.log(getter(obj).school.class1.student._)//50
console.log(getter(obj).school1.class11.student._)//undefined
When I answered, I was wondering if I could use defineProterty to make this function more compatible. Later, I found that the same logic could not be done only by using defineProterty , because defineProterty could not listen for set , get , which was revealed by proxy .
Menu