objeto literal javascript code example

Example 1: funcion dentro de objeto

//Calcular area rectangulo con objetos
//método
function rectangulo(base, altura) {
    this.base = base;
    this.altura = altura;
    this.calcularArea = function () { return this.base * this.altura; };
}
//instanciamos el objeto rectángulo:
var r1 = new rectangulo(2, 4);
//y llamamos al método área:
console.log(r1.calcularArea());

Example 2: object literal javascript

// Object literals are defined using the following syntax rules:
// A colon separates property name from value.
// A comma separates each name-value pair from the next.
// There should be no comma after the last name-value pair.

// If any of the syntax rules are broken, such as a missing comma or colon or curly brace,
// an error will be thrown.

var myObject = {
    sProp: 'some string value',
    numProp: 2,
    bProp: false
};

Example 3: FUNCION EN OBJETO JAVASCRIPT

//Manera 1
function nombreDelTipoDeObjeto (par1, par2, …, parN) {
this.nombrePropiedad1 = valorPropiedad1;
this.nombrePropiedad2 = valorPropiedad2;
this.método1 = function () { … código …. }
this.método2 = function (param1, param2, …, paramN) { … código …}
}
// Manera alternativa
function nombreDelTipoDeObjeto (par1, par2, …, parN) {
this.nombrePropiedad1 = valorPropiedad1;
this.nombrePropiedad2 = valorPropiedad2;
this.método1 = nombreFuncion1;
this.método2 = nombreFuncion2;
}
function nombreFuncion1 (par1, par2, …, parN) { … código … }
function nombreFuncion2 (par1, par2, …, parN) { … código … }

Example 4: acceder a propiedades objetos

nombreObjeto.nombrePropiedad

Si el método no recibe parámetros colocamos los paréntesis también, pero sin nada dentro.
miObjeto.miMetodo()

Tags:

Misc Example