This is the twenty-seventh day of my participation in the August Genwen Challenge.More challenges in August
Explicit with
Since JavaScript does not automatically implement the copying behavior, we need to implement the copying function manually. This functionality is called extend() in many libraries and frameworks, but is referred to as mixin() for easy comprehension.
Mixed copy
To review the mixin() function mentioned earlier:
// Very simple mixin() example
function mixin(sourceObj,targetObj){
for (var key in sourceObj){
// Copy only when it doesn't exist
if(! (keyintargetObj)){ targetObj[key] = sourceObj[key]; }}return targetObj;
}
Copy the code
It iterates over the sourceObj attribute and copies it if it is not in targeObj. Since we are copying after the target object is initialized, we must be careful not to overwrite the original properties of the target object.
If we copy first and then specialize the target object, we can skip the existence check:
// Another kind of mixed function, which may have rewrite risk
function mixin(sourceObj,targetObj){
for (var key in sourceObj){
targetObj[key] = sourceObj[key];
}
return targetObj;
}
var Vehicle={
/ /...
};
// First create an empty object and copy the Vehicle contents into it
var Car = mixin(Vehicle,{});
// Then copy the new content into Car
mixin({
wheels:4.drive:function(){
/ /...
}
},Car);
Copy the code
Both approaches explicitly copy non-overlapping content from Vehicle to Car.
Since both objects refer to the same function, this copying (or mixing) does not actually exactly mimic copying in class-oriented languages. Functions in JavaScript cannot be truly copied using standard, reliable methods, so only references to shared function objects can be copied. If you modify a shared function object, both sides are affected.
Explicit mixing is a nice mechanism for JavaScript, but it’s not as powerful as it looks. Although it can copy the properties of one object to another, the benefits are not great, and there are problems with function object references just described.
If you explicitly mix more than one object into the target object, you can partially mimic the behavior of multiple inheritance, but there is still no direct way to handle functions and attributes with the same name. One caveat: use explicit mixing only if it improves code readability, and avoid patterns that make code more difficult to understand or complicate object relationships.