如何使用函数初始化javascript
对象属性?
我尝试但失败的那个在下面提到:
var myObject = {
quatntity: 3,
toalAmount: function () {
return 599*this.quatntity;
}
请您建议正确的方法。
答案 0 :(得分:2)
你需要创建一个getter来读取in-literal兄弟值。
您忘记了get
运营商:
var ob={
quatntity: 3,
get toalAmount () {
return 599*this.quatntity;
}
};
alert(JSON.stringify(ob));
关于它们的好处是,toalAmount
的值会随着其他值的变化而自动更新,但它仍然可以序列化。
很多人忘记了吸气剂,或认为它是ES6的东西(有点看起来像),但它们自IE8 / ES5以来一直存在......
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
您也可能希望简单地将其设为传统方法,即使用“()”所需的类型,特别是如果您不需要JSON来包含该值。
答案 1 :(得分:0)
你错过了一个结束括号:
var myObject = {
quatntity: 3,
toalAmount: function () {
return 599*this.quatntity;
}
}
您现在可以通过调用myObject.toalAmount()
或者,您可以设置get
运算符(如dandavis建议的那样)以将值检索为myObject.toalAmount
旁注 - 你应该检查你的拼写:
答案 2 :(得分:0)
You are initializing the object the literal way. You can do it by using a function:
var myObject = function(){
var quantity = 3; //private variable
return {
totalAmount: function(){
return 599*quantity;
}
}
}()
Notice the () at the end of the function, so we are calling it and assigning the result to mybject. If you want to modify the quantity variable, you can create the function setter in the return value:
var myObject = function(){
var quantity = 3; //private variable
return {
totalAmount: function(){
return 599*quantity;
},
setQuantity: function(value){
quantity = value;
}
}
}()
You can also create a constructor function and use new
to instance new objects:
var MyObject = function(){
this.quantity = 3; //public variable
this.totalAmount = function(){
return 599*this.quantity;
}
}
var myObject = new MyObject();
myObject.totalAmount(); //1797
The constructor is commonly written with capital letter.
When you create an object using functions, variables with this.
prefix will be public and var
will be private