0
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.

S V
  • 570
  • 8
  • 21
  • @Vohuman. I am not looking to compare __proto__ and prototype properties. I am trying to understand why a particular lookup is not working. – S V Oct 27 '15 at 14:34
  • The question and accepted answer that @Vohuman linked clearly explains why your first lookup is failing. It also explains implicitly why you should not modify `__proto__`, which explains the second lookup. – rockerest Oct 27 '15 at 14:43

1 Answers1

0

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.

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513