2011-11-22 94 views
8

我是JavaScript新手... 我试图创建一个对象 - “花”。 每朵花都有它的性质:价格,颜色,高度...用属性创建一个对象,

有人可以给我一个想法如何建立它?

创建一个对象,然后改变他的属性?

:-)

+0

正常的JavaScript对象?你不会需要jQuery的 –

回答

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

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

适用于单身物件。 – CSharper

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

有一个对象,你也可以绑定功能。如果你想有多个花卉对象应使用以下的,因为你可以轻松地创建新的鲜花,它们都将有您所添加的功能:

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

谢谢,尼尔斯......非常有帮助! – BorisD

+0

已经更新了我的帖子,尝试了JSON格式内部的函数,'this'对象引用了元素,所以如果你想开始使用函数,你可以同时使用这两个元素。 – Niels

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

要检索值:

var price = flower.price; 

要更改属性值:

flower.price = newPrice; 
1

下面是创建与公共/私人部分对象(图案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(); 
相关问题