What would this . f be in Javascript?

Asked

Viewed 164 times

4

Taking a look at a tutorial on Javascript I came across the following code snippet:

let user = {
  name: "John"
};

function sayHi() {
  console.log(`Hello ${this.name}`);
}

user.f = sayHi;  // dúvida
user.f();  // retorna Hello John

I understood that if the f of the association of the function with user is returned to me Hello and the this name. is returned as a id or hash or something like that randomly:

let user = {
  name: "John"
};

function sayHi() {
  console.log(`Hello ${this.name}`);
}

user = sayHi;
user();  // retorna Hello ...

So my doubts are as follows:

  • what would this f
  • how it associates the object to function
  • what would be the random values when I do not use the f
  • 1

    .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 function sayHi is "referenced", and it can be declared later, read: https://answall.com/q/13364/3635 on functions.

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

  • Blza @Guilhermenascimento understood. Thanks man!

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

  • @Ivanferrer right, in the tutorial is addressed about this too.

2 answers

8


1°: what would this f?

In this example:

let user = {
  name: "John"
};

function sayHi() {
  console.log(`Hello ${this.name}`);
}

user.f = sayHi;  // dúvida
user.f();  // retorna Hello John

In doing user.f = sayHi, you say pro Javascript: update the property for me f that is inside the object user, if there is no property, create this property f and attribute to it the value sayHi, that in that case it would be a função. So to the user user.f(), he returns "Hello".

2°: how it associates the object to function?

It is in the above answer, it creates this new property f and associates to this property, the function sayHi, in the first example. In the second example, it overwrites the variable user with the value of the function sayHi.

3°: what would be the random values when not using f?

In this case you associated the user with a "memory reference" of the sayHi, the random characters would be because of the this.name, that in this case has no more reference, would be a "garbage"*, because there is no more property name in the user.

*UPDATE: The @bfavaretto explained what would be the "hash" or "garbage":

What you’re calling garbage or hash is actually the name of a HTML element (iframe) used in the code preview here . If this is executed in a normal window will come Undefined. Because when you performs a function outside the object context, this inside it points to the window.

  • Good answer man, I will accept Maniero’s for a chronological question, he answered a little earlier, but, the two explain very well. Thanks!

  • Actually mine was before hahah but good, the important thing is that it helped you!

  • Kkkk truth man, now that I see ;)

  • So @Maniero on top he said that the hash is a reference from memory, I think the last paragraph that might be removed the word hash

  • 1

    This ele cria uma nova propriedade e associa a essa propriedade should be ele cria uma nova propriedade e associa a essa função? This is confusing nesse caso você teria a função sayHi(), it would have the function or have the value returned by a possible return? After all he’s already "running"

  • Hmm right, I’ll wait to see if he edits.

  • Edited corrections to avoid confusing parts.

  • 2

    What you’re calling garbage or hash is actually the name of an HTML element (iframe) used in the code preview here . If this is executed in a normal window it will come Undefined. Because when you perform a function outside the object context, this inside it points to the window.

  • @bfavaretto Do not want to insert an answer with your vision?

  • I had noticed this difference even, but had not connected me in this, I will edit the answer with your contribution @bfavaretto

Show 5 more comments

5

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

  • Thanks Maniero, once again!

  • 3

    It is not garbage, JS never exposes memory (it would be serious if you did that). See https://answall.com/questions/421218/o-que-seria-este-f-javascript#comment818688_421221

  • @bfavaretto gave an edited, did not mean in the same sense of the C garbage, just something that should not be available, edited, see if it became clearer.

  • 1

    I got it, I really thought I was talking about the "classic" garbage:) It was better with Edit. Taking advantage of the relaxation of concepts, has a certain undefined behavior in these references to this out of contexts in which it makes sense. In Strict mode this does not occur, this turns null instead of pointing to the global object.

  • Good to know, I still don’t like null, but it’s better

Browser other questions tagged

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