Search code examples
javascriptprototypedelegation

How does Javascript prototype linkage and delegation work?


function func() {}

func.prototype.foo = "Var"

console.log(func.foo) // undefined

var foonew = new func() 

console.log(foonew.foo) // Var

Why is func.foo unable to lookup the prototype property??

function func() {}

func.__proto__.foo = "Var"

console.log(func.foo) // Var

var foonew = new func() 

console.log(foonew.foo) // undefined

When using the proto reference to the prototype it looks like the behavior is reversed.


Solution

  • You are confusing the [[Prototype]] with the prototype.

    The [[Prototype]], also known as __proto__, is an internal property which determines from which object the current object should inherit from.

    The prototype is a property of constructors which determines the [[Prototype]] of newly created instances.

    This is fully explained in __proto__ VS. prototype in JavaScript.

    You can achieve both behaviors by setting the [[Prototype]] of the constructor to its prototype. You can use setPrototypeOf (or __proto__) for that:

    function func() {}
    Object.setPrototypeOf(func, func.prototype);
    func.prototype.foo = "Var";
    
    func.foo;       // "Var"
    new func().foo; // "Var"
    

    I don't recommend it, though.