Doubt about prototype

Asked

Viewed 84 times

7

I have a basic question in prototype in Javascript, is the following:

function MeuObjeto() {}

obj1 = new MeuObjeto
MeuObjeto.nome = "Lucas"

console.log(obj1.nome)

Upshot:

Undefined

I am in doubt as to why the prototype when instantiating the Meuobjeto is Meuobjeto.prototype and not Meuobjeto?

Like if I do:

obj1.__proto__ = MeuObjeto

The console.log(obj1.nome) will result in "Lucas" but I understand that if I did MeuObjeto.prototype.nome = "Lucas" would not give Undefined as before when he did obj1.nomand yet I didn’t understand the utility of by default when instantiating a function to be defined the prototype __proto__ as (nomeobjeto).prototype instead of the (nomeobjeto).

1 answer

2


When a constructor function is created, the object prototype is created simultaneously.

And when you do:

MeuObjeto.nome = 'Lucas'

What is happening is that you are creating the 'name' property on function Meuobjeto and not in her prototype and for the inheritance chain to be created correctly we need to use the new.

And making:

obj1.nome 
  • He will try to search this property first on obj1

  • And then on prototype of MeuObjeto

I think this post can better clarify your doubt of why the properties stay in the prototype and not in function: https://www.instagram.com/p/B6yCC4dAhhC/

  • Good evening, thank you very much, like I understood this to be creating in the function Meuobjeto and not in her prototype but just wanted to know why was designed so Javascript, type I saw the instagram and liked me very much clarified a lot of things but I still found it kind of forced her explanation, after all in the fifth image to use Dog.prototype.bark to add bark to Dog.prototype and everyone could use would be the same thing if the proto do Dog fosse Dog instead of Dog.prototype hence simply making Dog.bark could be used by all instances of Dog equal Dog.prototype.bark makes.

  • I imagine that the prototype was a way to "simplify" the hierarchy. Almost like a "pointer" to a list, to facilitate the path.

  • Got it, helped me a lot, thank you!

  • Remembering that this is my opinion. I have no evidence that this is the reason for the prototype.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.