gpt4 book ai didi

orm - sequelizejs 中的 instanceMethods 和 getterMethods 有什么区别?

转载 作者:行者123 更新时间:2023-12-01 13:47:47 29 4
gpt4 key购买 nike

sequelize.define("aModel", {
text: DataTypes.TEXT
}, {
instanceMethods: {
getme1: function() {
return this.text.toUpperCase();
}
},
getterMethods: {
getme2: function() {
return this.text.toUpperCase();
}
}
});

InstanceMethodsgetterMethods似乎完成了同样的事情,允许访问虚拟键。你为什么要用一个而不是另一个?

最佳答案

您使用 Model.method() 调用的实例方法,但是如果您有一个名为 text 的 getter 方法,它会在您执行 instance.text 时被调用。同样,当您执行 instance.text = 'something' 时,会使用 setter 方法。

例子:

var Model = sequelize.define("aModel", {
text: DataTypes.TEXT
}, {
instanceMethods: {
getUpperText: function() {
return this.text.toUpperCase();
}
},
getterMethods: {
text: function() {
// use getDataValue to not enter an infinite loop
// http://docs.sequelizejs.com/en/latest/api/instance/#getdatavaluekey-any
return this.getDataValue('text').toUpperCase();
}
},
setterMethods: {
text: function(text) {
// use setDataValue to not enter an infinite loop
// http://docs.sequelizejs.com/en/latest/api/instance/#setdatavaluekey-value
this.setDataValue('text', text.toLowerCase());
}
}
});

Model.create({
text: 'foo'
}).then(function(instance) {
console.log(instance.getDataValue('text')); // foo
console.log(instance.getUpperText()); // FOO
console.log(instance.text); // FOO

instance.text = 'BAR';

console.log(instance.getDataValue('text')) // bar
console.log(instance.text); // BAR
});

关于orm - sequelizejs 中的 instanceMethods 和 getterMethods 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34540536/

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