【问题标题】:ES6 default value - help understand the conceptES6 默认值 - 帮助理解概念
【发布时间】:2020-04-17 09:39:29
【问题描述】:

我正在努力发展我的 JS 技能并开始利用 ES6。

我知道您可以分配默认值,我正在模块中尝试:

export var updateWidget = function (type = 'image', {
    previewId = '.image-preview',
    filepath = 'content/articles',
    baseUrl = 'http://dummy.com',
    thumbSize = '400x400'
}) {


    var options = {
            previewId: previewId,
            type: type
        },
        fileElements = {
            filepath: filepath,
            thumbPath: null,
            baseUrl: baseUrl,
            thumbSize: thumbSize

        },
}

如果我然后像这样启动对象:

new updateWidget('image'
            ).update('5059-081.png');

我得到一个与默认对象相关的cannot read property undefined。如果我这样做:

new updateWidget('image', {}
            ).update('5059-081.png');

有效。

我需要将一个空白对象传递给模块以使其工作似乎很奇怪,我本来希望将它完全排除在外,默认值仍然可以工作。

我正在寻求更新我用来充分利用 ES6 的当前模块模式,但一步一步来。

那么,我怎样才能设置默认值并且只需要发送一个对象呢?最佳做法是什么?

谢谢

【问题讨论】:

    标签: javascript ecmascript-6 es6-modules


    【解决方案1】:

    第二个参数需要一个将被解构的对象。

    当它被解构时,产生的每个变量都被赋予一个默认值,以防对象没有匹配的属性。

    如果没有传递参数,则没有给出应该解构的默认值。

    您可以将空对象设置为默认值。

    export var updateWidget = function (type = 'image', {
        previewId = '.image-preview',
        filepath = 'content/articles',
        baseUrl = 'http://dummy.com',
        thumbSize = '400x400'
    } = {})
    

    (注意最后一行的变化)

    【讨论】:

    • 谢谢 - 我误解了,我认为只需在其中设置默认对象就足够了 - 现在完全有意义 - 传递一个默认的空白对象。谢谢
    【解决方案2】:

    这是因为您已经设置了第二个参数的默认属性,但您还没有将其设为可选。

    只需将其默认值设置为空对象,如下所示:

    export var updateWidget = function (type = 'image', {
        previewId = '.image-preview',
        filepath = 'content/articles',
        baseUrl = 'http://dummy.com',
        thumbSize = '400x400'
    } = {}) { // <= Setting the default value as empty object
    
    
        var options = {
                previewId: previewId,
                type: type
            },
            fileElements = {
                filepath: filepath,
                thumbPath: null,
                baseUrl: baseUrl,
                thumbSize: thumbSize
    
            },
    }
    

    【讨论】:

    • 太好了 - 谢谢。非常感谢您的解释
    【解决方案3】:

    由于第二个参数是undefined,解构不适用于未定义的值。

    你可以这样做const getItem = (type = "image", { previewId. ="abc" } = {}) =&gt; {}

    【讨论】:

    • 谢谢——我现在明白了默认的空白对象——你能解释一下箭头的用法吗?我已经阅读了一些关于这些的内容,但还没有深入了解
    • 一个箭头函数没有自己的绑定,这意味着如果你在其中使用this,那么this将代表它的父绑定
    • 再次感谢 - 我现在已经阅读了这篇文章,你说的很有道理
    【解决方案4】:

    如果你想让第二个参数可选,你需要为它提供一个默认值。您已经为正在执行的解构提供了默认值,但没有提供实际参数本身。结果,您试图解构值 undefined,这就是您收到错误的原因。

    为要解构的参数提供默认值,如下所示:

        export var updateWidget = function (type = 'image', {
            previewId = '.image-preview',
            filepath = 'content/articles',
            baseUrl = 'http://dummy.com',
            thumbSize = '400x400'
        } = {}) {
    // −−^^^^^
    

    现场示例:

    const updateWidget = function (type = 'image', {
        previewId = '.image-preview',
        filepath = 'content/articles',
        baseUrl = 'http://dummy.com',
        thumbSize = '400x400'
    } = {}) {
        console.log(`type = ${type}`);
        console.log(`previewId = ${previewId}`);
        console.log(`filepath = ${filepath}`);
        console.log(`baseUrl = ${baseUrl}`);
        console.log(`thumbSize = ${thumbSize}`);
    }
    console.log("Call 1:");
    updateWidget();
    console.log("Call 2:");
    updateWidget(undefined, {filepath: "/different/path"});
    console.log("Call 3:");
    updateWidget("mytype", {filepath: "/different/path"});
    .as-console-wrapper {
        max-height: 100% !important;
    }

    【讨论】:

    • 谢谢 - 现在说得通了,解构是一个新概念 - 更多的研究和感谢您的解决方案和 sn-p
    • @Ray - 不用担心! FWIW,我在几个月后出版的新书中详细介绍了解构和参数默认值。如果您有兴趣,请查看我的个人资料了解详细信息。 ;-)
    • 人群 - 谢谢 - 我会留意的 - :)
    【解决方案5】:

    以下是有效的,但是当提供undefined 时,它会抛出TypeError,因为undefined 不是适合解构的类型。

    function foo({ a = 'a' }) {
      console.log(a)
    }
    
    foo() // TypeError: Cannot read property 'a' of undefined

    为了让您的代码优雅地失败,您可以提供一个空对象作为默认参数。 它这样工作的原因是,默默地从这个错误中“拯救”程序员会降低语言的表达能力,因为无法区分(在这种情况下)将 undefinednull 传递给这样的函数并传递一个空对象。

    function foo({ a = 'a' } = {}) {
      console.log(a)
    }
    
    foo() // 'a'

    如果你不使用解构,那么默认参数将以正常方式生效:

    function foo(a = 'a') {
      console.log(a)
    }
    
    foo() // 'a'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 2022-01-10
      相关资源
      最近更新 更多