2016-08-20 66 views
0

我想用coffeescript在js類中包裝一些pliugin選項。返回一個具有咖啡類的

在平原JS我有

toastr.options = { 
    "closeButton" : false, 
    "debug" : false, 
    "positionClass" : "toast-bottom-right", 
    "onclick" : null, 
    "showDuration" : "300", 
    "hideDuration" : "1000", 
    "timeOut" : "8000", 
    "extendedTimeOut" : "1000", 
    "showEasing" : "swing", 
    "hideEasing" : "linear", 
    "showMethod" : "fadeIn", 
    "hideMethod" : "fadeOut" 
} 

隨着CoffeeScript的

class @ToastrOptions 
    constructor: -> 
    'closeButton': false 
    'debug': false 
    'positionClass': 'toast-bottom-full-width' 
    'onclick': null 
    'showDuration': '300' 
    'hideDuration': '1000' 
    'timeOut': '8000' 
    'extendedTimeOut': '1000' 
    'showEasing': 'swing' 
    'hideEasing': 'linear' 
    'showMethod': 'fadeIn' 
    'hideMethod': 'fadeOut' 

toastr.options = new ToastrOptions 

當我檢查toastr.options的已經是空的{}。爲什麼?

+0

你的JS是沒有階級,它是一個對象字面,那你爲什麼使用與CoffeeScript的'class' ??? – Bergi

回答

0

下面的代碼定義了ToastrOptions類。它定義了toHash方法,它返回帶有預定義值的普通js對象。 引用你的代碼 - 你把這個普通的對象定義直接放在構造函數方法中,因爲new AnyClass的結果總是這個類的新實例,無論你放在構造函數方法中。下面

代碼測試的http://coffeescript.org/

class ToastrOptions 
    toHash: -> 
    closeButton: false 
    debug: false 
    positionClass: 'toast-bottom-full-width' 
    onclick: null 
    showDuration: '300' 
    hideDuration: '1000' 
    timeOut: '8000' 
    extendedTimeOut: '1000' 
    showEasing: 'swing' 
    hideEasing: 'linear' 
    showMethod: 'fadeIn' 
    hideMethod: 'fadeOut' 


console.log(new ToastrOptions().toHash())