0

下面的示例包含一些格式化函数和一个在字段和格式化函数之间映射的对象。

MyObject = function() {};
MyObject.prototype.formatters = {
    'money': function(value) { return "€" + value },
    'hyperlink': function(value) { return "<a href='"+value+"'>"+value+"</a>";
}
MyObject.prototype.fieldFormatters = {
    'field1': this.formatters.money,
    'field2': this.formatters.hyperlink
}

不幸的是,上下文fieldFormatterswindow在评估时,所以我无法参考this.formatters。是否有替代方法来参考this.formatters或解决此问题的更好方法?

4

2 回答 2

1

您需要参考prototype,而不是实例:

MyObject.prototype.fieldFormatters = {
    'field1': MyObject.prototype.formatters.money,
    'field2': MyObject.prototype.formatters.hyperlink
};
于 2013-03-11T17:57:44.093 回答
1

只有函数在上下文中执行。

MyObject = function() {};
MyObject.prototype.formatters = {
    'money': function(value) { return "&euro;" + value },
    'hyperlink': function(value) { return "<a href='"+value+"'>"+value+"</a>";
}
MyObject.prototype.getFieldFormatters = function () {
    // here this is instance of MyObject having correct __proto__
    return {
        'field1': this.formatters.money,
        'field2': this.formatters.hyperlink
    }
}

但是你可以做一个技巧:使用getters

Object.defineProperty(MyObject.prototype, "fieldFormatters", {get : function () {
    // here this is instance of MyObject having correct __proto__
    return {
        'field1': this.formatters.money,
        'field2': this.formatters.hyperlink
    }
}})
于 2013-03-11T17:59:03.693 回答