javascript 创建一个具有属性的对象,
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8224680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create an object with properties,
提问by BorisD
I am new to javascript... I trying to create an object- "Flower". Every Flower has it properties: price,color,height...
我是 javascript 新手......我试图创建一个对象 - “花”。每朵花都有它的属性:价格、颜色、高度...
Can somebody give me an idea how to build it?
有人可以告诉我如何构建它吗?
Create an object and then change his properties?
创建一个对象然后改变他的属性?
:-)
:-)
回答by Dezigo
flower= {
price : function() {
console.log('Price is 78 $');
},
color: 'red',
height : 23
};
flower.price();
flower.height ;
回答by Niels
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:
有一个对象,您还可以将函数绑定到该对象。如果您想拥有多个 Flower 对象,则应使用以下内容,因为您可以轻松创建新的 Flowers 并且它们都将具有您添加的功能:
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());
回答by abcde123483
var flower = {"height" : 18.3, "price":10.0, "color":"blue"}
回答by Nir Geier
Here is a pattern to create object with public/private section(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();
回答by Premanshu
var flower = {"propertyName1": propertyValue1, "propertyName2": propertyValue};
To retrieve the values:
要检索值:
var price = flower.price;
To change property values:
要更改属性值:
flower.price = newPrice;