JavaScript:没有eval的闭包中的自动getter和setter中的默认参数? [英] JavaScript: default arguments in automatic getters and setters in closures without eval?

查看:77
本文介绍了JavaScript:没有eval的闭包中的自动getter和setter中的默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这个问题是对最近提出的问题的跟进 JavaScript:自动getter和setter in closures in without eval?

Note: this question is a follow up of the recently asked question JavaScript: automatic getters and setters in closures without eval? .

该问题的要点如下:如何在闭包中自动为范围变量提供getter和setter - 而不使用 eval 声明。有海报,提供代码演示如何使用 eval ,并且用户提供了以下答案,不需要 eval

The gist of that question was as follows: "How can one automatically provide getters and setters for scoped variables in a closure - without the use of the eval statement". There the poster, provided code demonstrating how to do so with eval and the user gave the following answer which does not require eval:

function myClosure() {
  var instance = {};
  var args = Array.prototype.slice.call(arguments);
  args.forEach(function(arg) {
    instance[arg] = function(d) {
      if (!arguments.length) return arg;
      arg = d;
      return instance;
    };
  })
  return instance;
};

这个问题是关于如何为范围变量设置默认值将使用上述函数设置/获取。

This question is about how to have default values for the scoped variables which are to be set / get with the above function.

如果我们只是将默认值添加到变量 v3 我们得到以下结果:

If we simply add a default value to the variable v3 we get the following:

function myClosure() {
  var v3 = 2
  var instance =  {};
  var args = Array.prototype.slice.call(arguments);
  args.forEach(function(arg) {
    instance[arg] = function(d) {
      if (!arguments.length) return arg;
      arg = d;
      return instance;
    };
  })
  return instance;
}

var test = myClosure("v1", "v2", "v3") // make setters/getters for all vars
test.v1(16).v2(2) // give new values to v1, v2
console.log(test.v1() + test.v2() + test.v3()) // try to add with default v3
// 18v3

我没想到。

那么如何为变量提供默认值?

So how can I provide a default value to the variables?

注意:请构建以下实现生成getter的实现/ setters初始化(允许代码作者预先定义所有应该有getter和setter的变量)

Note: please build off the following implementation which generates the getters / setters on initialization (allowing the code author to pre-define all variables which should have getters and setters)

function myClosure() {
  var instance =  function () {};
  var publicVariables =['v1', 'v2', 'v3']
  function setup() {
    var args = Array.prototype.slice.call(arguments);
    // if called with a list, use the list, otherwise use the positional arguments
    if (typeof args[0] == 'object' && args[0].length) { args = args[0] }
    args.forEach(function(arg) {
      instance[arg] = function(d) {
        if (!arguments.length) return arg;
        arg = d;
        return instance;
      };
    })
  }
  setup(publicVariables)
  // setup('v1', 'v2', 'v3')  also works 
  return instance;
}

var test = myClosure()
test.v1(16).v2(2)
console.log(test.v1() + test.v2() + test.v3())



问题:



如何使用自动getter和setter在此设置(上面的代码块)中使用默认值?

Question:

How to use default values in this set up (above code block) with automatic getters and setters?

推荐答案

你的意思是这样的:

function myClosure(...vars) {
  const instance =  {};
  vars.forEach(varArg => {
    let name = undefined;
    let value = undefined;
    if (typeof varArg == 'string')
    {
       name = varArg;
    }
    else
    {
       name = Object.keys(varArg)[0];
       value = varArg[name];
    }
 
    instance[name] = function(d) {
      if (!arguments.length) return value;
      value = d;
      return instance;
    };
  })
  return instance;
}

const test = myClosure(
  { "v1": 1 },
  "v2",
  { "v3": 3 },
);
// Print some defaults.
console.log(test.v1());
console.log(test.v2());

test.v1(16).v2(42) // give new values to v1, v2
console.log(test.v1(), test.v2(), test.v3())

Proxies,哎呀。

Proxies, for the heck of it.

function myClosure(...vars) {
  const instance = vars.reduce((obj, { name, value }) => {
    obj[name] = value;
    return obj;
  }, {});

  let proxy;
  const handler = {
    get: function(target, prop) {
      return (...args) => {
        if (args.length == 0)
          return instance[prop];

        instance[prop] = args[0];

        return proxy;
      };
    }
  };

  proxy = new Proxy(instance, handler);
  return proxy;
}

const test = myClosure(
  { name: "v1", value: 1 },
  { name: "v2" },
  { name: "v3", value: 3 }
);
// Print some defaults.
console.log(test.v1());
console.log(test.v2());
console.log(test.vNew());

test.v1(16).v2(42).vNew(50); // give new values to some variables.
console.log(test.v1(), test.v2(), test.v3(), test.vNew())

这篇关于JavaScript:没有eval的闭包中的自动getter和setter中的默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆