Search code examples
javascriptfunctionobjectprototypal-inheritancedelegation

JavaScript prototype delegation in function


I am trying to learn Javascript but I am finding this prototype concept very confusing someone helps me with this code snippet

var func = function (){};
func.prototype = {m:9};

func.prototype.m; // That logs 9

func.m; // That logs undefined 

Why is the delegation not working in this case?


Solution

  • What you have is a constructor function that has m in its prototype.

    var func = function (){};
    func.prototype = {m:9};
    
    console.log( func.prototype.m ); // That logs 9
    

    The prototype is assigned not to the function itself but to instances created by this function:

    var f = new func();
    
    console.log( f.m ); // That also logs 9
    

    This is where your m is.

    For this to also log 9

    func.m
    

    you'd have to have m in Function.prototype because the prototype of func is Function

    Function.prototype.m = 9;
    
    console.log( func.m ); // Logs 9