简体   繁体   English

带有setter / getter的构造函数返回字符串

[英]Constructor with setter/getter returns string

I just received a quick JS test to complete from my employer, and I got lost. 我刚接到一个快速的JS测试来完成我的雇主,我迷路了。 On the last question he asked me to do the following: 关于最后一个问题,他让我做了以下事情:

Using JavaScript, implement a 'chart' function according to the example: 使用JavaScript,根据示例实现“图表”功能:

Note: '===' is used below to communicate the expected output. 注意:下面使用'==='来传达预期的输出。

var myBarChart = chart(); 
myBarChart.type() === 'line';
myBarChart.type('bar'); 
myBarChart.type() === 'bar'; 
myBarChart() === "Here's your bar chart!";

var myScatterChart = chart().type('scatter'); 
myScatterChart() === "Here's your scatter chart!";

I said I can't do it, but is it invalid, or I just lost my mind completely? 我说我不能这样做,但它是无效的,还是我完全失去了理智? It isn't a constructor, as it's not having new parameter. 它不是构造函数,因为它没有新参数。 And also it wouldn't return a string, if that would accept any Setters. 并且如果它接受任何Setter,它也不会返回字符串。 Or am I wrong? 还是我错了?

Please, answer my question, as I'm feeling dumb now. 请回答我的问题,因为我现在感到愚蠢。

There's a number of concepts at play here. 这里有很多概念。

First of all, you can have a function that returns another function: 首先,您可以使用一个返回另一个函数的函数:

 function chart() {
      var fn = function() {
          console.log('You are calling the anonymous function!')
      };

      return fn;
 }

 let myBarChart = chart();
 myBarChart();

Secondly, you can attach additional fields to functions. 其次,您可以将附加字段附加到函数。 (If you come from a C# or Java background that might feel wrong, but you can do this in Javascript). (如果您来自可能感觉不对的C#或Java背景,但您可以在Javascript中执行此操作)。

 function chart() {
      var fn = function() {
          console.log('You are calling the anonymous function!')
      };

      // Attaching a new field
      fn.type = function() {
          console.log('Now you are calling the type function!');
      }
      return fn;
 }

 let myBarChart = chart();
 myBarChart.type();

Thirdly, there's a pattern in javascript where you use the same function as a getter or setter. 第三,javascript中有一个模式 ,你使用与getter或setter相同的函数。 It's discussed on the Software Engineering Stackexchange site . 它在Software Engineering Stackexchange站点上进行了讨论。

function chart() {
     var typeValue = 'line';

     var fn = function() {
         return (typeValue === 'line' ? "Here's your line chart!" : "Here's your bar chart!");
     };


     fn.type = function(value) {
          if(typeof(value) !== 'undefined') {
             typeValue = value;
             return fn;
          } else {
             return typeValue;
          }
     };

     return fn;
}

let myChart = chart();
myChart.type() === 'line';
myChart() === "Here's your line chart!";
let setterReturnValue = myChart.type('bar');
setterReturnValue === myChart;
myChart() === "Here's your bar chart!";

The example he provided demonstrates what you can do with these three concepts. 他提供的示例演示了如何使用这三个概念。

It's definitely possible. 这绝对是可能的。 The first line var myBarChart = chart(); 第一行var myBarChart = chart(); tells you that chart is a function, so you have: 告诉你chart是一个函数,所以你有:

function chart ( ) {

}

The next line myBarChart.type() tells you that the value returned by chart() is an object with a type property that is itself a function that returns 'line' . 下一行myBarChart.type()告诉您chart()返回的值是一个具有type属性的对象,该属性本身就是一个返回'line'的函数。 So now you have: 所以现在你有:

function chart ( ) {
    return {
        type: function ( ) {
            return 'line';
        }
    }
}

The next line myBarChart.type('bar'); 下一行myBarChart.type('bar'); doesn't tell you anything on its own, but the line after that tells us that subsequent calls to .type() should return the new type, so .type() is acting as both a setter and getter (analogous to jQuery's val , for example). 它本身没有告诉你什么,但是之后的行告诉我们后续调用.type()应该返回新类型,所以.type()既作为setter又作为getter(类似于jQuery的val ,例如)。 So now you have something like: 所以现在你有类似的东西:

function chart ( ) {
    var storedType = 'line';
    return {
        type: function ( newType ) {
            if ( newType )
                storedType = newType;
            else
                return storedType;
        }
    }
}

The next line myBarChart() tells us that the return value of chart actually needed to be a function, not a plain object. 下一行myBarChart()告诉我们chart的返回值实际上需要是一个函数,而不是普通对象。 That function needs to return 'Here\\'s your ' + storedType + ' chart!' 该函数需要返回'Here\\'s your ' + storedType + ' chart!' and it needs to have the type property that our object had before. 它需要具有我们的对象之前具有的type属性。 The easiest way to add a property to a function is to store that function in a variable and then add the property. 向函数添加属性的最简单方法是将该函数存储在变量中,然后添加属性。 So the result is: 结果是:

function chart ( ) {
    var storedType = 'line';
    var func = function ( ) {
        return 'Here\'s your ' + storedType + ' chart!';
    };
    func.type = function ( newType ) {
        if ( newType )
            storedType = newType;
        else
            return storedType;
    }
    return func;
}

The next two line var myScatterChart = chart().type('scatter'); 接下来的两行var myScatterChart = chart().type('scatter'); tells you that when .type is called with an argument, it should return the same function as was returned by calling chart() . 告诉你,当使用参数调用.type时,它应返回与调用chart()返回的函数相同的函数。 That can be done by either returning func or this to complete the answer: 这可以通过返回func或者this来完成答案:

function chart ( ) {
    var storedType = 'line';
    var func = function ( ) {
        return 'Here\'s your ' + storedType + ' chart!';
    };
    func.type = function ( newType ) {
        if ( newType ) {
            storedType = newType;
            return func;
        } else
            return storedType;
    }
    return func;
}

You need to know that functions are first class objects. 您需要知道函数是第一类对象。 It means that like any other normal object it can have properties. 它意味着像任何其他普通对象一样,它可以具有属性。 Knowing that you could implement this function something like this. 知道你可以实现这样的功能。 Here is one possible solution: 这是一个可能的解决方案:

function chart () {
  const obj = () => `Here's your ${obj.type()} chart!`
  let __type = 'line'

  obj.type = type => {
    if (type) {
      __type = type
      return obj
    }
    return __type
  }
  return obj
}
  1. var myBarChart = chart() - chart must return new function. var myBarChart = chart() - chart必须返回新函数。

  2. myBarChart.type() === 'line' - returned function must have type property which is another function, which returns some sort of type ( line or chart ). myBarChart.type() === 'line' - 返回的函数必须具有type属性,这是另一个函数,它返回某种类型( linechart )。

  3. myBarChart.type('bar') - when used as a setter, set __type to new value. myBarChart.type('bar') - 当用作setter时,将__type设置为新值。 Let's keep it as local variable __type . 我们将它保存为局部变量__type

  4. chart returns a function which when called returns a string with type information. chart返回一个函数,当被调用时返回一个带有类型信息的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 构造函数中的getter / setter - Getter/setter in constructor 构造函数,getter和setter方法中的Object.defineProperty - Object.defineProperty in constructor, getter and setter method JavaScript:创建函数,该函数返回一个返回具有getter / setter功能的输出的函数 - JavaScript: Create Function that returns a function that returns output with getter / setter capabilities 没有吸气剂的二传手 - A setter with no getter 使用带有 Getter/Setter 的构造函数初始化 JavaScript/ES5 对象 - Initialization of a JavaScript/ES5 object using a constructor with Getter/Setter 将“ this”指针从对象构造函数传递给JS中的setter / getter - Passing “this” pointer from object constructor to setter/getter in JS 从Json Schema使用构造函数,getter和setter生成Javascript类 - Generating Javascript class with constructor, getter and setter from Json Schema Typescript getter/setter 属性数组返回错误值 - Typescript getter/setter property array returns wrong value JavaScript-对象原型中的Getter / Setter无法正常工作。 Getter返回最后一个元素 - JavaScript - Getter/Setter in Objects's Prototype is not working. Getter returns last element 函数的Setter / Getter在调用函数时将函数转换为字符串? - Setter/Getter for function turns function into a string when the function is called?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM