1

我想将 getter/setter 传递给函数,但不能。甚至可以在 JS 中做(或模仿)这样的事情吗?

我尝试使用 getter/setter 调用一个函数,但它(很明显)不起作用,我尝试了“apply”和“call”,但它仍然(不知何故)不起作用。

function foo(x, y) {
  var i;

  for (i = 0; i < 5; ++i)
    console.log(x, y);
}

var args = [];

Object.defineProperties(args, {
  "0": {
    "set": function() { },
    "get": Math.random
  },

  "1": {
    "set": function() { },
    "get": function() { return new Date().getMilliseconds(); }
  }
});

foo.apply(this, args);

预期 5 个不同的结果,却得到 5 个相同的结果。

4

2 回答 2

1

问题是.apply将您的“数组”转换为arguments对象,因此您的访问器只会被评估一次。

您可以通过将数组直接传递给函数来使您的示例正常工作:

function foo(arr) {
  for (var i = 0; i < 5; ++i)
    console.log(arr[0], arr[1]);
}

var args = [];
Object.defineProperties(args, {
  "0": {
    "set": function() { },
    "get": Math.random
  },

  "1": {
    "set": function() { },
    "get": function() { return new Date().getMilliseconds(); }
  }
});

foo(args);

于 2019-07-23T21:34:04.247 回答
0

不,这是不可能的。args数组被转换为 中的单个值的列表,apply然后值本身作为参数传递。

函数参数永远不会表现出 getter 功能。有一些可怕的技巧可以使某个范围内的标识符充当 getter/setter,但是您永远不应该这样做,而且无论如何您都需要在函数内部这样做。

最好的办法是期望xy参数的函数,并在内部显式调用它们foo

于 2019-07-23T21:37:55.327 回答