^^Js. Object.

 

Example of one way to create a simple object:

 

var obj = new Object();

obj.a = 3;
obj.b = 4;
obj.fun = function()
          {
          return this.a + this.b;
          };
          
alert("The Answer is " + obj.fun());

 

Here’s what is going on:

  1. The first line creates a new object, and gives a reference to the object to a variable named obj. The keyword new tells JavaScript to allocate some memory for this object. There are other things JavaScript can create using new.
    1. Object must be capitalized and spelled exactly as shown.
    2. The parentheses at the end are necessary, too.
  2. The next two lines create two new variables in the object referenced by obj. Note that
    a dot separates the reference to the object from the variable inside the object. Other than that, variables inside objects are just like regular variables: they can appear on either the left or right side of assignment statements, and they can hold any types of value. Note about variables inside objects:
    1. you do not use var when you want to create one, you just assign an initial value to it and it gets created automatically.
    2. of interest primarily if you already know another programming language: in JavaScript you don’t have to declare what variables an object is going to contain ahead of time. Just pick a name, assign a value to it, and it gets created.
  3. The fourth through seventh lines show how you can put a function inside an object. Technically, the function is separate from the object, and the object variable (fun in this case) holds a reference to it, but that’s not a key concept at this point. What is important is to note that the function doesn’t have a name. Remember, when defining a
    function, you usually put the keyword function, followed by the name of the function, followed by the parentheses.
    1. Note that inside the function, the variables in the object can be referenced using the special object name, this. (Yes, you could also refer to the variables as obj.a and obj.b, but that would take away one of the things you can do with object, so using this is normally better.)
  4. Finally, the example shows the object’s function being called from inside an alert() function call. What do you think happens when this code is run? The alert function will put a message box in the middle of the screen. In this case, it will look like this: alert box with 7 in it

 

Esempio: Creazione di un oggetto

// costruttore
function MyObj(attributeA, attributeB)
{
  this.A = attributeA
  this.B = attributeB
}
 
obj = new MyObj('red',1000)  // crea un Oggetto
alert(obj.A)                 // accede ad un attributo di obj
alert(obj["A"])              // accede con notazione del vettore associativo