This is the twenty-sixth day of my participation in the August Genwen Challenge.More challenges in August

Mixed with

JavaScript’s object mechanism does not automatically perform the behavior of copying when it comes to inheritance or instantiation. Simply put, there are only objects in JavaScript, and there are no “classes” that can be instantiated. Objects are not copied to other objects, they are associated. Since all classes in other languages behave like clones, JavaScript developers have come up with a way to mimic the behavior of copying classes: mixin. There are two types of mixin: explicit and implicit.

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.

    // 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;
}
var Vehicle = {
    engines:1.ignition: function(){
        console.log("Turn on my engine");
    },
    drive:function(){
        this.ignition();
        console.log("Steering and moving forward!"); }};var Car = mixin(Vehicle,{
    wheels:4.drive:function(){
        Vehicle.drive.call(this);
        console.log("Rolling on all" + this.wheels +"wheels!"); }});Copy the code

There is now a copy of the Vehicle attributes and functions in the Car. Technically, functions are not actually copied, only function references. So the ignition attribute in Car is just a reference to the ignition() function copied from Vehicle. In contrast, the attribute Engines copies the value 1 directly from Vehicle. Car already has the drive attribute, so this attribute is not rewritten by mixin, which retains the same attribute defined in Car, and implements the “subclass” to “parent class” attribute rewrite.

polymorphism

Consider this statement: vehicle.drive.call (this). This is explicit polymorphism. JavaScript did not have a relatively polymorphic mechanism prior to ES6, so since both Car and Vehicle have drive() functions, we must use absolute references in order to specify the calling object. We specify the Vehicle object by name display and call its drive() function.

But if you call vehicle.dirve () directly, the this in the function call is bound to the Vehicle object instead of the Car object. This does not work as expected, so we use call to ensure that Drive () is executed in the context of the Car object.