Javascript getter
Javascript getter
鉴于以下代码 foo
、bar
和 baz
都有效吗?使用 get
关键字有什么好处?
var getValue = function () {
return 'value';
}
var foo = {
value: getValue(),
};
var bar = {
get value() {
return getValue();
},
};
var baz = {
get value() {
return 'value';
},
};
console.log('foo.value', foo.value); // foo.value value
console.log('bar.value', bar.value); // bar.value value
console.log('baz.value', baz.value); // baz.value value
Given the following code are foo, bar and baz all effectively the same?
不,一点也不。
foo
将有一个 value
属性,这将是调用 getValue
的 结果 foo
创建时,以后不会调用getValue
。
bar
将有一个 value
属性,当像 bar.value
一样访问时,调用 getValue
和 return 是它的 return 值。
baz
将有一个 value
属性 具有显式值 'value'
.
区别是:
- 是否调用
getValue
- 当调用
getValue
时
这对于一些日志记录和 getValue
:
的稍微更新的版本来说更明显
var getValue = function () {
var value = Math.floor(Math.random() * 1000);
console.log("getValue called, returning " + value);
return value;
}
console.log("Creating foo");
var foo = {
value: getValue(),
};
console.log("Creating bar");
var bar = {
get value() {
return getValue();
},
};
console.log("Creating baz");
var baz = {
get value() {
return 42;
},
};
console.log("Calling foo");
console.log('foo.value', foo.value);
console.log("Calling bar");
console.log('bar.value', bar.value);
console.log("Calling baz");
console.log('baz.value', baz.value);
.as-console-wrapper {
max-height: 100% !important;;
}
getter 的优点(和缺点)是您可以执行逻辑(例如调用 getValue
)以响应看似简单的 属性 查找(bar.value
,而不是 bar.value()
或 bar.getValue()
).
鉴于以下代码 foo
、bar
和 baz
都有效吗?使用 get
关键字有什么好处?
var getValue = function () {
return 'value';
}
var foo = {
value: getValue(),
};
var bar = {
get value() {
return getValue();
},
};
var baz = {
get value() {
return 'value';
},
};
console.log('foo.value', foo.value); // foo.value value
console.log('bar.value', bar.value); // bar.value value
console.log('baz.value', baz.value); // baz.value value
Given the following code are foo, bar and baz all effectively the same?
不,一点也不。
foo
将有一个value
属性,这将是调用getValue
的 结果foo
创建时,以后不会调用getValue
。bar
将有一个value
属性,当像bar.value
一样访问时,调用getValue
和 return 是它的 return 值。baz
将有一个value
属性 具有显式值'value'
.
区别是:
- 是否调用
getValue
- 当调用
getValue
时
这对于一些日志记录和 getValue
:
var getValue = function () {
var value = Math.floor(Math.random() * 1000);
console.log("getValue called, returning " + value);
return value;
}
console.log("Creating foo");
var foo = {
value: getValue(),
};
console.log("Creating bar");
var bar = {
get value() {
return getValue();
},
};
console.log("Creating baz");
var baz = {
get value() {
return 42;
},
};
console.log("Calling foo");
console.log('foo.value', foo.value);
console.log("Calling bar");
console.log('bar.value', bar.value);
console.log("Calling baz");
console.log('baz.value', baz.value);
.as-console-wrapper {
max-height: 100% !important;;
}
getter 的优点(和缺点)是您可以执行逻辑(例如调用 getValue
)以响应看似简单的 属性 查找(bar.value
,而不是 bar.value()
或 bar.getValue()
).