Instantiated functions

Asked

Viewed 26 times

2

function relogio(elemento){
    console.log(elemento)
}
$('[wm-relogio]').each((i,e) => new relogio(e))

What’s the difference between relogio and new relogio instantiated? Both of which work?

1 answer

4


First example

The difference is that one is a simple function and when you use the new you create an object, see this small example, I am calling the function and the object, realize that when calling the function the return was undefined while calling the object it returns to me an object {}.

function relogio(elemento){

}
   
console.log(relogio("teste"));
console.log(new relogio("teste"));

Second example

See this other example, when I create the "car1" it is an object, that is, I created the object, I created an instance, now "car1" exists, but when I use the "Car" function and assign to "car2" I did not create an instance, that is, the function only performs and nothing more than that, it does not create a new object.

Then trying to run "car2.make" generates an error, since "car2" is not an object, "car2" and simply a variable with the value undefined.

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

var car1 = new Car('Eagle', 'Talon TSi', 1993);
var car2 = Car('Eagle', 'Talon TSi', 1993);

console.log(car1.make);
console.log(car2.make);

Third example using your code

function relogio(elemento){
    console.log(elemento)
}
$('[wm-relogio]').each((i,e) => new relogio(e))

You said "Since the two work", they work partially, you call a array function

(i,e) => new relogio(e)

This function is equivalent to

function(i, e){
    return new relogio(e);
}

If you do as the example above, it will return an instance/object of "clock", when creating an instance of clock it runs its constructor console.log(elemento), showing the value of "element" in the console, but if you do

function(i, e){
    return relogio(e);
}

Without the reserved word new, it will do the same, but without returning the "clock" object, it will simply perform the "clock" function and will return undefined.

So if the function needs the "clock" object you must use the reserved word new, but if you don’t need this return best use without the word new, thus avoids creating an object unnecessarily.

Completion

When you use the reserved word new it creates an instance, and what is an instance is the creation of an object, and then you can use that object, and when I run a function, it simply "does its job" and that’s it, it doesn’t create something new.

Browser other questions tagged

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