Create an object with properties,

I am new to javascript ... I am trying to create an object - "Flower". Each color has properties: price, color, height ...

Can someone give me an idea how to build it?

Create an object and then change its properties?

:-)

+8
javascript
source share
5 answers
flower= { price : function() { console.log('Price is 78 $'); }, color: 'red', height : 23 }; flower.price(); flower.height ; 
+10
source share

Have an object to which you can also attach functions. In order to have several Flower objects, you need to use the following: you can easily create new Flowers, and all of them will have functions that you added:

 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(); 

If you want some kind of array to just use an object literal, but you need to set properties and functions for each object you create.

 var flower = { price : 12, color : "green", myfunction : function(){ alert(this.price); } }; flower.price = 20; alert(flower.price); alert(flower.myfunction()); 
+9
source share
 var flower = {"height" : 18.3, "price":10.0, "color":"blue"} 
+1
source share

Here is a template for creating an object with public / private sections

 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(); 
+1
source share
 var flower = {"propertyName1": propertyValue1, "propertyName2": propertyValue}; 

To get the values:

 var price = flower.price; 

To change property values:

 flower.price = newPrice; 
0
source share

All Articles