Doubt methods Javascript

Asked

Viewed 43 times

0

Greetings

I have a question about methods in javascript. Can anyone tell me if this is a method and what kind of method this is.

nomeMetodo : function (){
  //code
}

It wouldn’t be like this...

function nomeMetodo () {
  //code
}
  • It’s a yes method. With literal objects, we can invoke functions the way you exemplified them. Read about objects. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Tworksworks_com_Objetos#Definindo_m%C3%A9all

  • The first is a Method, you use it inside an object, in this case nomeMetodo would be a property of the object whose value is a function. The second is a Function normal.

1 answer

0

The two ways are right.

javascript works with the concept of anonymous function, is called anonymous precisely because you do not need to define a name to it, as below.

function (){ //code }

This anonymous function will usually be used when you need to assign the function to a variable

var nomeMetodo = function (){ //code }

or create a function in an object:

var x = { a: 2, nomeMetodo: function() { return this.a; } }

In this case if you call x.nameMetodo() it will return the value of a

Everything will depend on how you use your function... if you want to know a little more, I recommend starting with MDN documentation.

  • 1

    I should add your answer that there is a difference in declaring a function, and assigning a function to a variable. See https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-function_functionname

Browser other questions tagged

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