what would this f
A member of an object created at this time, like any other with nothing special. Or if you prefer it is an element of a array associative that passes as object, which is what are objects in JS. It is only a normal variable within an object/array, there is no feature that differs from other things, has nothing magical in it, is equal to name
only that in name
you saved a string
and in f
saved a function (yes, you can store functions in variables). see more in What is the difference between the functions var name = Function() and Function name()?.
how it associates the object to function
The assignment you are making in this object member is making this association, is taking the name of the function (without parentheses that would call the function) and this name is a reference to the effective function, and is holding in the variable f
that belongs to user
.
what would be the random values when I don’t use f
Then in the second example something else happened, you reset the object user
completely and no longer has what he had, that is, nor has the field name
, now user
only has the reference for the function sayHi
and nothing else. When you call him with user()
is having an element printed that does not exist, i.e. this.name
no longer exists, so it takes a junk value in memory (in the sense of something that is there but should not, in my opinion). I don’t think this behavior should happen, but it’s JS, you know how it is.
This is because there is a closure, but in the case does not have a value associated with that variable, but JS always tries to give some result, so he considers that there must be something there, in fact according to the comment of bfavaretto he finds that name in the element iframe
that is exposed (in my opinion already exposed, unduly, but that is how the JS is).
.f
could be anything (have any value), it’s basically the same as doing this:let user = {
 name: "John", f: sayHi
};
, but in the case.f =
you are setting the property later. Note that using the functionsayHi
is "referenced", and it can be declared later, read: https://answall.com/q/13364/3635 on functions.– Guilherme Nascimento
ps: Remember that if you pass an object by a parameter you can change the value of the properties in reference by updating the set object in the parameter, but this is another story.
– Guilherme Nascimento
Blza @Guilhermenascimento understood. Thanks man!
– LeAndrade
It seems to be a created attribute that would represent a new method: function (f) type:
obj.func = function() { ...}
. Only one Obs: if you have several instances of the same object, put it in the prototype. Otherwise each object will have its own copy of the method, it is usually a waste of resource.– Ivan Ferrer
@Ivanferrer right, in the tutorial is addressed about this too.
– LeAndrade