2011-11-22 26 views
8

Soy nuevo en javascript ... Estoy tratando de crear un objeto- "Flor". Cada flor tiene sus propiedades: precio, color, altura ...Crear un objeto con propiedades,

¿Alguien me puede dar una idea de cómo construirlo?

Crea un objeto y luego cambia sus propiedades?

:-)

+0

¿Un objeto normal de JavaScript? No necesitarás jQuery para eso –

Respuesta

10
flower= { 
price : function() { 
    console.log('Price is 78 $'); 
}, 
color: 'red', 
height : 23 
}; 

flower.price(); 
flower.height ; 
+0

Bueno para objetos individuales. – CSharper

1
var flower = {"height" : 18.3, "price":10.0, "color":"blue"} 
9

tener un objeto, donde también se pueden unir a las funciones. A continuación se debe usar si usted quiere tener varios objetos de flores, porque se puede crear fácilmente nuevas flores y todos ellos tendrán las funciones que ha añadido:

function Flower(price, color, height){ 
    this.price = price; 
    this.color= color; 
    this.height= height; 

    this.myfunction = function() 
    { 
     alert(this.color); 
    } 
} 

var fl = new Flower(12, "green", 65); 
fl.color = "new color"); 

alert(fl.color); 
fl.myfunction(); 

Si usted quiere tener una especie de matriz sólo tiene que utilizar un objeto literal, pero necesita establecer las propiedades y funciones para cada objeto que cree.

var flower = { price : 12, 
       color : "green", 
       myfunction : function(){ 
        alert(this.price); 
       } 
}; 
flower.price = 20; 
alert(flower.price); 
alert(flower.myfunction()); 
+0

Gracias, Niels ... ¡Muy útil! – BorisD

+0

He actualizado mi publicación, he intentado tener una función dentro del formato JSON, y el objeto 'this' se refiere al elemento, por lo que puede usar ambos si desea comenzar a usar funciones. – Niels

0
var flower = {"propertyName1": propertyValue1, "propertyName2": propertyValue}; 

Para recuperar los valores:

var price = flower.price; 

para cambiar los valores de propiedad:

flower.price = newPrice; 
1

Aquí es un patrón para crear objetos con sección pública/privada (s)

var MyObj = function() 
{ 
    // private section 
    var privateColor = 'red'; 

    function privateMethod() 
    { 
     console.log('privateMethod. The color is: ', privateColor); 
    } 

    // The public section 
    return 
    { 
     publicColor : 'blue', 
     publicMehtod: function() 
     { 
      // See the diffrent usage to 'this' keyword 
      console.log('publicMehtod. publicColor:', this.publicColor, ', Private color: ', privateColor); 
     }, 
     setPrivateColor: function(newColor) 
     { 
      // No need for this 
      privateColor = newColor; 
     }, 
     debug: function() 
     { 
      this.publicMehtod(); 
     } 
    }; 
} 

var obj1 = new MyObj(); 
obj1.publicMehtod(); 
obj1.setPrivateColor('Yellow'); 
obj1.publicMehtod(); 

var obj2 = new MyObj(); 
obj2.publicMehtod(); 
Cuestiones relacionadas