1

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?

fool-dev
  • 7,671
  • 9
  • 40
  • 54

2 Answers2

4

By doing func.prototype = {m:9};, you are setting the 'prototype' property of your func variable to {m:9}.

When you call, func.m, you try to access the 'm' property of your func variable, which you never set before.

Instead, you previously set the 'm' property of the object func.prototype.

If you want to set the property 'm' from your variable func, simply do func.m = 9;

Zenoo
  • 12,670
  • 4
  • 45
  • 69
3

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
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106