JS比较函数返回闭包

时间:2018-12-03 12:36:32

标签: javascript function compare closures

下面的代码片段显示了一些方法调用的比较。

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

1 个答案:

答案 0 :(得分:0)

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

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

const getPatientName = getPatient('name');