Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an object with properties,

Tags:

javascript

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

Can somebody give me an idea how to build it?

Create an object and then change his properties?

:-)

like image 945
BorisD Avatar asked Nov 22 '11 09:11

BorisD


People also ask

What are an objects properties?

Object properties differentiate objects from other objects. The basic properties of an object are those items identified by its four-part name (name, type, instance, and version) and also include owner, status, platform, and release.

How can you create an object in JavaScript?

Creating a JavaScript ObjectCreate a single object, using an object literal. Create a single object, with the keyword new . Define an object constructor, and then create objects of the constructed type. Create an object using Object.create() .

What is object property in JavaScript?

JavaScript Properties Properties are the values associated with a JavaScript object. A JavaScript object is a collection of unordered properties. Properties can usually be changed, added, and deleted, but some are read only.


1 Answers

Have an object, where you can also bind functions to. The following should be used if you want to have multiple Flower objects, because you can easily create new Flowers and they will all have the functions you have 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 to have a sort of array just use an object literal, but you need to set the 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());
like image 180
Niels Avatar answered Oct 01 '22 12:10

Niels