One question a day, keep thinking
The title
Implement mixin functions, similar to object. assign, that recursively merge other source objects themselves and inherited enumerable properties into target target objects.
var a = {a: 1};
mixin(a, {b: 2}, {c: 3});
console.log(a); // {a: 1, b: 2, c: 3}
Copy the code
The specific implementation
// Check whether it is an object type
function isObj(value) {
returnvalue ! =null && (typeof value === 'object' || typeof value === 'function');
}
// Iterate over every property on obj, call copy, bind to this
function forIn(obj, fn, thisArg) {
for (var key in obj) {
if (fn.call(thisArg, obj[key], key, obj) === false) {
break; }}}// Attribute values other than '__proto__', 'constructor', 'prototype'
function isValidKey(key) {
returnkey ! = ='__proto__'&& key ! = ='constructor'&& key ! = ='prototype';
};
// Copy objects
function copy(val, key) {
if(! isValidKey(key)) {return;
}
var obj = this[key];
if (isObj(val) && isObj(obj)) {
mixin(obj, val);
} else {
this[key] = val; }}// Merge multiple objects, change the value of target
function mixin(target) {
var length = arguments.length,
index = 0;
while (++index < length) {
var obj = arguments[index];
if(isObj(obj)) { forIn(obj, copy, target); }}return target;
}
Copy the code
Implementation approach
Parameters:
-
Target (Object) : the Object to be merged.
Steps:
- use
while
traversearguments
Member of, starting at position 1; If the value type being traversed is an objectforIn
Method, otherwise skip. - call
forIn
Method is called by iterating over the current objectcopy
Copy the method copy
Method to determine the corresponding attribute value, if not'__proto__', 'constructor', 'prototype'
One of these three returnstrue
Otherwise returnfalse
. If the current value to be copied is an object, it is called recursivelymixin
Method, right herethis
Pointing is essentiallymixin
The object that needs to be merged is executedmixin
Method changes the original target value.
If you find something wrong or can be improved, please point it out in the comments section. If you think it’s good or helpful, please like it, comment on it or share it with us. Thank you