创建一个属性为的对象,

Create an object with properties,

本文关键字:对象 属性 一个 创建      更新时间:2023-09-26

我是javascript新手。。。我试图创建一个对象——"花"。每朵花都有它的特性:价格、颜色、高度。。。

有人能给我一个如何建造的主意吗?

创建一个对象,然后更改其属性?

:-(

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

有一个对象,你也可以在其中绑定函数。如果你想有多个Flower对象,应该使用以下内容,因为你可以轻松地创建新的Flower,它们都将具有你添加的函数:

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

如果你想要一个数组,只需要使用一个对象文字,但你需要为你创建的每个对象设置属性和函数。

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

下面是一个创建带有公共/私有部分的对象的模式

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

检索值:

var price = flower.price;

更改属性值:

flower.price = newPrice;