Create an object with properties,

前端 未结 5 1724
名媛妹妹
名媛妹妹 2021-01-17 16:01

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 i

5条回答
  •  鱼传尺愫
    2021-01-17 16:05

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

提交回复
热议问题