2016-05-23 73 views
1

我有默認參數的ES6類,像這樣:巴貝爾ES6類使用默認參數解構未定義

constructor({ 
    // defaults 
    defaultOne  = 'default value one', 
    defaultTwo  = ['default','value','two], 
    defaultThree = 'default value three, 
}) { 
    this.defaultOne = defaultOne 
    this.defaultTwo = defaultTwo 
    this.defaultThree = defaultThree 

    return this 
} 

當我創建它按預期工作時,我提供值類的一個實例。

new Class({defaultOne: 'one',defaultTwo: ['t','w','o'], defaultThree: 'three'}) 

但是,當我實例沒有值的實例:

new Class() 

它拋出一個未定義的錯誤。這種方法似乎在標準函數聲明/表達式中工作得很好。任何想法我在這裏失蹤?

在此先感謝您的幫助。

回答

0

雖然它似乎沒有在規範允許你直接解構類的參數,該解決方案提供了一個非常類似的語法:

class Test { 
    constructor(options) { 
     let { 
     defaultOne : defaultOne = 'default one value', 
     defaultTwo : defaultTwo = 'default two value', 
     defaultThree : defaultThree = 'default three value' 
     } = (options) ? options:{}; 

     this.defaultOne = defaultOne; 
     this.defaultTwo = defaultTwo; 
     this.defaultThree = defaultThree; 

     this.init(); 
    } 

    init() { 
    console.log(this.defaultOne); 
    console.log(this.defaultTwo); 
    console.log(this.defaultThree); 
    } 
} 

new Test({defaultOne: 'Override default one value'}); 
new Test(); 

ES6 Babel test

Compiled Babel ES5

3

我同意這是一個有點醜陋,但它發生是因爲巴貝爾將其轉化爲如下形式:

constructor(_ref) { 
    var _defaultOne = _ref.defaultOne; // « this is where it goes wrong. _ref = undefined 
} 

您正在設置對象屬性的默認值,但不是對象本身的默認值。所以這是可以修復的。如果巴貝爾爲我們做了這件事,那會很好,但事實並非如此。

爲了解決這個問題,提供了參數對象默認,而不是:

// es6 
const foo = ({ bar = 'baz' }) => {}; 

// transpiled 
var foo = function foo(_ref) { 
    var _ref$bar = _ref.bar; 
    var bar = _ref$bar === undefined ? 'baz' : _ref$bar; 
}; 

你需要寫

// es6 
const foo = ({ bar = 'baz'} = {}) => {}; 

// transpiled 
var foo = function foo() { 
    var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; 

    var _ref$bar = _ref.bar; 
    var bar = _ref$bar === undefined ? 'baz' : _ref$bar; 
}; 

是完整的,你的榜樣將成爲:

constructor({ 
    // defaults 
    defaultOne  = 'default value one', 
    defaultTwo  = ['default','value','two'], 
    defaultThree = 'default value three', 
} = {}) { // « notice the change on this line 
    this.defaultOne = defaultOne 
    this.defaultTwo = defaultTwo 
    this.defaultThree = defaultThree 
} 

new Class({defaultOne: 'one',defaultTwo: ['t','w','o'], defaultThree: 'three'}) 
new Class()