gpt4 book ai didi

javascript - 在原型(prototype)对象分配中将实例引用为 'this'

转载 作者:行者123 更新时间:2023-12-02 18:56:02 24 4
gpt4 key购买 nike

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

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

但是你可以使用一个技巧:使用 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
}
}})

关于javascript - 在原型(prototype)对象分配中将实例引用为 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15345284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com