Javascript getter

问题: Given the following code are foo, bar and baz all effectively the same? What if any is the advantage of using the get keyword? var getValue = function () { return 'valu...

问题:

Given the following code are foo, bar and baz all effectively the same? What if any is the advantage of using the get keyword?

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

回答1:

Given the following code are foo, bar and baz all effectively the same?

No, not at all.

  • foo will have a value property that will be the result of calling getValue when foo was created, and will not call getValue later.

  • bar will have a value property that, when accessed like bar.value, calls getValue and returns its return value.

  • baz will have a value property with the explicit value 'value'.

The differences are:

  • Whether getValue is called
  • When getValue is called

This is more obvious with some logging and with a slightly updated version of 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;;
}

The advantage (and disadvantage) to a getter is you can execute logic (such as calling getValue) in response to what looks like a simple property lookup (bar.value, rather than bar.value() or bar.getValue()).

  • 发表于 2019-03-31 10:07
  • 阅读 ( 218 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除