[英]Set a value of an object in javascript from a function without calling the function
I know I'm over complicating this but I'm curious. 我知道我已经使这个复杂化了,但我很好奇。
So I have a function: 所以我有一个功能:
var setSize = function(selectedSize){
var split = {
size: val.sizes.split(','),
tcin: val.tcin.split(','),
idx: function(){
return this.size.indexOf(selectedSize);
}
};
console.log(split.idx)
}
HTML: HTML:
<p>choose a size</p>
<div onClick="setSize('small')>small</div>
QUESTION: 题:
Is this possible to have split.idx to have a value of say 0
not a value of function. 这可能使split.idx的值等于
0
而不是函数的值。
In a modern browser, you can use a getter for the idx
property so that it becomes a calculated property. 在现代的浏览器中,可以对
idx
属性使用吸气剂,以使其成为计算所得的属性。
The programmmer would access it as split.idx
, but the value would still be calculated by a function. 程序员可以将其作为
split.idx
访问,但该值仍将由函数计算。
Details on getters here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get 此处有关吸气剂的详细信息: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/get
var setSize = function(selectedSize){
var split = {
size: val.sizes.split(','),
tcin: val.tcin.split(','),
get idx() {
return this.size.indexOf(selectedSize);
}
};
console.log(split.idx)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.