2013-03-11 22 views
0

下面的示例包含一些格式函數和一個在字段和格式化函數之間進行映射的對象。在原型對象分配中將實例引用爲'this'

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 
} 

不幸的是,在fieldFormatters上下文是window在評價的時候,所以我不能引用this.formatters。有沒有其他方法可以參考this.formatters或更好的方法來解決這個問題?

回答

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 
    } 
}}) 
+0

好想法,但'__defineGetter__'缺乏跨瀏覽器支持。我用上下文調用函數來提出一個替代方案:'MyObject.prototype.fieldFormatters =(function(){return ...})call(MyObject.prototype);'。但最終取決於個人偏好。 – bcoughlan 2013-03-11 18:55:10

+1

@bcoughlan,有一個ECMAScript版本5 [Object.defineProperty](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty)。你可以用它來定義getters(我更新了我的代碼片段)。 – 2013-03-11 19:01:39

1

您需要參考回到prototype,不是一個實例:

MyObject.prototype.fieldFormatters = { 
    'field1': MyObject.prototype.formatters.money, 
    'field2': MyObject.prototype.formatters.hyperlink 
}; 
相關問題