在看immutability-helper
的源码,对其中一段函数很疑惑
update.isEquals = function(a, b) { return a === b; };
function update(object, spec) {
if (typeof spec === 'function') {
return spec(object);
}
if (!(Array.isArray(object) && Array.isArray(spec))) {
invariant(
!Array.isArray(spec),
'update(): You provided an invalid spec to update(). The spec may ' +
'not contain an array except as the value of $set, $push, $unshift, ' +
'$splice or any custom command allowing an array value.'
);
}
invariant(
typeof spec === 'object' && spec !== null,
'update(): You provided an invalid spec to update(). The spec and ' +
'every included key path must be plain objects containing one of the ' +
'following commands: %s.',
Object.keys(commands).join(', ')
);
var nextObject = object;
var index, key;
getAllKeys(spec).forEach(function(key) {
if (hasOwnProperty.call(commands, key)) {
var objectWasNextObject = object === nextObject;
nextObject = commands[key](spec[key], nextObject, spec, object);
// update.isEquals(nextObject, object) 为true那不就是 nextObject 一定等于 object, 再写 nextObject = object 有什么意义
if (objectWasNextObject && update.isEquals(nextObject, object)) {
nextObject = object;
}
} else {
var nextValueForKey =
type(object) === 'Map'
? update(object.get(key), spec[key])
: update(object[key], spec[key]);
if (!update.isEquals(nextValueForKey, nextObject[key]) || typeof nextValueForKey === 'undefined' && !hasOwnProperty.call(object, key)) {
if (nextObject === object) {
nextObject = copy(object);
}
if (type(nextObject) === 'Map') {
nextObject.set(key, nextValueForKey);
} else {
nextObject[key] = nextValueForKey;
}
}
}
})
return nextObject;
}
这段函数有什么意义? update.isEquals(nextObject, object)
不就表示两者相等了
if (objectWasNextObject && update.isEquals(nextObject, object)) {
nextObject = object;
}
isEquals
为暴露的接口,用户可以自身定义myUpdate.isEquals = ...
比如将
isEquals
定义为深度检查,那仍将nextObject = object