【问题标题】:JS compare function that returns closure返回闭包的JS比较函数
【发布时间】:2018-12-03 12:36:31
【问题描述】:

下面的代码sn-p展示了几个方法调用的对比。

console.clear();
const al = (sub, property) => (state) => (state[sub][property]);

const getPatient = (property) => al('patient', property);
const getAppointment = (property) => al('appointment', property);

const state = {
  patient: {name: 'jos', lastname: 'ke'},
  appointment: {date: '01-01-1900'},
};

getPatient('name') === getPatient('lastname'); // should evaluate to false
getPatient('name') === getAppointment('date'); // should evaluate to false
getPatient('name') === getPatient('name'); // should evaluate to true, but is false

但是,我希望最后一个比较结果为true。我们如何编写比较结果使其评估为true

【问题讨论】:

    标签: javascript function compare closures


    【解决方案1】:

    函数getPatientgetAppointmentgetPatient返回一个闭包;每次调用这些函数时,都会返回一个新的闭包,并且它们不会严格等效 (===)。

    如果您需要创建这些闭包并能够比较它们,只需创建一次闭包并将它们分配给一个变量:

    const getPatientName = getPatient('name');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多