reactive.js

reactive.js
复制


function reactive(val) {
  const isPrimitive =
    val instanceof Number || val instanceof String || val instanceof Boolean;
  return new Proxy(
    {
      [Symbol.toPrimitive]: () => val,
      valueOf: () => val.valueOf(),
      toString: () => val.toString(),
    },
    {
      get(target, prop, receiver) {
        if (isPrimitive) {
          return Reflect.get(target, prop, receiver);
        } else {
          if (prop === Symbol.toPrimitive) {
            return target[prop];
          }
          return Reflect.get(val, prop, receiver);
        }
      },
      set(target, prop, value, receiver) {
        if (isPrimitive) {
          val[prop] = value;
        } else {
          return Reflect.set(val, prop, value);
        }
      },
    }
  );
}

var count = reactive(1);
console.log(+count); // 1
console.log(++count); // 2
console.log(++count); // 3
console.log(count + ""); // '3'
count -= 10;
console.log(+count); // -7

// count = 4;
console.log(+count); // 4

var form = reactive({
  username: "username",
  password: "password",
  address: {
    city: "a",
    code: 233,
  },
});

console.log(form.username);

form.username = "axetroy";

console.log(form.username);

form.address.city = "123123";

console.log(form.address.city);


大牛们的评论:朕有话说

还没有人评论哦,赶紧抢沙发!