引用实例为'this'在原型对象分配中

Referencing instance as 'this' in prototype object assignment

本文关键字:对象 分配 原型 实例 引用 this      更新时间:2023-09-26

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

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或更好的方法来解决这个问题?

只在上下文中执行函数。

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
    }
}

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

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

您需要引用回prototype,而不是实例:

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