JavaScript:如何从没有`return`的方法中检索值

时间:2016-12-02 05:46:09

标签: javascript function methods pikaday

我正在尝试修改现有的datepicker插件(Pikaday),以在某些呈现的HTML中显示所选日期(在插件中呈现)。

我已经确定以下setDate方法/函数返回我想要使用的日期字符串,但我不确定如何提取它并在我的函数中使用它。

setDate方法显示为:

 setDate: function(date, preventOnSelect)
    {
        if (!date) {
            this._d = null;

            if (this._o.field) {
                this._o.field.value = '';
                fireEvent(this._o.field, 'change', { firedBy: this });
            }

            return this.draw();
        }
        if (typeof date === 'string') {
            date = new Date(Date.parse(date));
        }
        if (!isDate(date)) {
            return;
        }

        var min = this._o.minDate,
            max = this._o.maxDate;

        if (isDate(min) && date < min) {
            date = min;
        } else if (isDate(max) && date > max) {
            date = max;
        }

        this._d = new Date(date.getTime());
        setToStartOfDay(this._d);
        this.gotoDate(this._d);

        if (this._o.field) {
            this._o.field.value = this.toString();
            fireEvent(this._o.field, 'change', { firedBy: this });
            //I want to return `this._o.field.value`
        }
        if (!preventOnSelect && typeof this._o.onSelect === 'function') {
            this._o.onSelect.call(this, this.getDate());
        }
    }

我希望返回this._o.field.value

有谁知道如何抓住这个并在我的功能中使用它?

PS,我来自PHP OOP背景,所以我对JS OOP的理解可能缺乏,抱歉。我的HTML呈现功能:

renderHeading = function(instance, c, year, month, days)
{
    var opts = instance._o;
    var html = '<div class="pika-heading">';
    html += '<h3 class="pika-heading-year">' + year + '</h3>';
    html += '<h1 class="pika-heading-date">' + opts.i18n.weekdaysShort[day] + ', ' + opts.i18n.monthsShort[month] + '</h1>';
    return html += '</div>';
}

1 个答案:

答案 0 :(得分:0)

if (this._o.field) {
            this._o.field.value = this.toString();
            window.myDateProperty = this._o.field.value;// Add your own property
            fireEvent(this._o.field, 'change', { firedBy: this });
            //I want to return `this._o.field.value`-- I wont prefer returning as that alters the library code.
        }

现在window.myDateProperty包含this._o.field.value的{​​{1}}将在javascript文件中提供。

PS:总是做检查:

if(window.myDateProperty){
  //use window.myDateProperty
}