【问题标题】:Is there a way to use an Accessor Function to define a property of an object in JS?有没有办法使用访问器函数在 JS 中定义对象的属性?
【发布时间】:2021-10-30 16:27:42
【问题描述】:

我有两个输入:

data = {"year": 2021}
valueAccessor = (d) => d["year"];

这两个输入可以是动态的,所以我不知道对象或函数中会是什么。

我想创建一个新对象,并使用 Accessor 函数为该对象设置值。有没有办法做到这一点?

output = {}
output = definePropertyUsingFunction(output, valueAccessor, newValue)

【问题讨论】:

  • 不,没有...

标签: javascript object functional-programming


【解决方案1】:

简短的回答是“不”。但是……

如果您处于某种受控的学习环境中,您可以尝试一些事情。

如果你知道一个事实:

  • 您的 getter 函数是纯函数(无副作用),并且
  • 您的 getter 函数始终访问 1 个属性,

你可以

  • 使用 Proxy 跟踪属性访问
  • 调用getter 来触发它(同样,如果这是一个纯函数,它不应该有任何副作用)
  • 向记录的属性写入值

这是一个概念证明:

const data = { year: 2000, month: 1, day: 28 };

const getYear = obj => obj.year;
const getMonth = obj => obj.month;
const toString = obj => `${obj.year}/${obj.month}/${obj.day}`;

const writeViaSimpleGetter = (obj, value, getter) => {
  let propName = null;
  
  const proxy = new Proxy(obj, {
    get: (target, key) => {
      if (propName) throw "Multiple properties accessed";
      propName = key;
    }
  });
  
  // Call the getter
  getter(proxy);
  
  if (!propName) throw "No property accessed";
  
  return { ...obj, [propName]: value };
}

// Simple getters work:
console.log(
  writeViaSimpleGetter(data, 2021, getYear)
)

console.log(
  writeViaSimpleGetter(data, 12, getMonth)
)

// This throws:
try {
  console.log(
    writeViaSimpleGetter(data, "oops", toString)
  )
} catch(e) { console.log("ERROR:", e) }

// This also throws:
try {
  console.log(
    writeViaSimpleGetter(data, "oops", () => {})
  )
} catch(e) { console.log("ERROR:", e) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2020-03-12
    • 2021-12-14
    • 2016-03-31
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    相关资源
    最近更新 更多