There are two ways to use objects in JavaScript: with Object Literal using key-value pairs; or using a function that will be the object constructor.
Object Literal : In this usage mode, you just define a variable with braces {} and each key-value separated by a comma.
Function : Define a function that will be the basis for instantiating new objects. In this case, as it is in a block of a function, you write programming statements normally, using a semicolon at the end of each statement.
In your example, Code 1 refers to using a function that defines a blueprint (or a class, although versions of JavaScript before ES6 do not have classes).
In Code 2, you are using Object Literal. But I notice that you used Object.create, but I do not think you should use it that way because what happens is that when you pass Person to function Object.create , you create an object whose prototype is Person. When you change the name, for example, the name will be set to Person1, but you will still have the name in the prototype. To run an experiment, run your code in the Chrome Dev Tools Web Console (or console from another browser) and check the value of the Person1 variable in Code 2. You will see that the Person1 object has a property name with a Peter value, but also which has the pseudo-property __proto__
with the Person object as the prototype. And this object also has a property name that is null! So if you were not defined the name as Peter, JavaScript would look in the prototype to see if it has the property name (as it has, would show null, its value).
Anyway, I recommend using functions to create a blueprint pro object (i.e. class) and set the prototype as your example in Code 3 . That is, if you are instantiating objects of a kind of class. The way to make objects using literal objet is also valid, though for other occasions.
Here is a final note about prototype: attributes that are unique to each object (for example, name, age, height, weight, etc.) must be defined within the function that defines the blueprint pro object. The behavior of objects, things that are common to all of them (eg: talking, walking, sleeping, eating, drinking, etc.), should be defined using prototype. When you create an object based on a function definition, that object will have its own properties while the functions defined by prototype are common to all instances of that function class. In other words, everything that is defined via the prototype is only defined once while the attributes of the Person are created for each instance.
I hope you have helped. Just one touch for everyone that ES6 will soon become the default, so they can get used to using classes in JavaScript using the following form:
class Pessoa {
constructor(nome) {
this.nome = nome;
}
// Métodos protótipos
dizerNome() {
alert(this.nome);
}
}