JavaScript syntax

I keep finding some JavaScript that looks like an example below. Can someone explain this since I have not seen JavaScript written like this before.

What is "SomethingHere" and the colon? I'm used to seeing the myFunction () function, but not what is shown below.

SomethingHere: function () { There is code here that I understand. } 
+6
source share
5 answers

As some other answers show, this is an example of object notation. An object can be declared as follows:

 var myObj = new Object(); 

However, it can also be declared with an object literal record, for example:

 var myObj = { }; 

When using object literal syntax, you can immediately add methods and properties inside the open and close curly braces using the syntax name: value. For instance:

 var myObj = { name: 'Dave', id: 42, SomethingHere: function() { /* function body */ } }; alert(myObj.name); // Displays Dave alert(myObj.id); // Displays 42 myObj.SomethingHere(); // Executes method SomethingHere 

"SomethingHere", in this case, is a "method", which means that it is a function that is a member of the object. The special variable this has this value. In the following two function definitions, this refers to a browser window variable (assuming code is executed in the browser):

 function foo() { /* this.document refers to window.document */ /* this.location refers to window.location*/ } var bar = function() { /* Same as above, just a different syntax for declaring the function. /* this.document refers to window.document */ /* this.location refers to window.location*/ } 

In this example, however, this one refers to the enclosing object, myObj:

 var myObj = { name = 'Dave', id = 42, myMethod: function() { /* this.name refers to the name property of myObj, ie, 'Dave' */ /* this.id refers to the id property of myObj, ie, 42 */ /* this.location is undefined */ /* this.document is undefined */ } }; 
+1
source

This is an object literal notation. This is a way to declare objects using the following form:

 { propertyName: value } 

So for example:

 var obj = { fruit: "apple", id: 123, sayHello: function() { return "Hi"; } }; alert(obj.fruit); alert(obj.id); alert(obj.sayHello()); 
+7
source

Basically in this area / syntax you should have named arguments, and this is a way to get a function in an object.

+2
source

You can create an object in Javascript as follows:

 var obj = { a: 1, b: 2 }; 

You can also have attributes that are functions:

 var obj = { SomethingHere: function() { alert("hello"); }, b: 2 }; 
+2
source

EDITED: The reference to JSON is missing, as it may be misunderstood using the data format.

This is the designation of a JavaScript object. You can make a function like:

 var SomethingHere = function() { };
var SomethingHere = function() { }; 

or...

 var Singleton = { SomethingHere: function() { ... } }
var Singleton = { SomethingHere: function() { ... } } 
0
source

Source: https://habr.com/ru/post/896994/


All Articles