sequelizejs 中的 instanceMethods 和 getterMethods 有什么区别?
Whats the difference between instanceMethods and getterMethods in sequelizejs?
sequelize.define("aModel", {
text: DataTypes.TEXT
}, {
instanceMethods: {
getme1: function() {
return this.text.toUpperCase();
}
},
getterMethods: {
getme2: function() {
return this.text.toUpperCase();
}
}
});
InstanceMethods and getterMethods 似乎完成了同样的事情,允许访问虚拟键。你为什么要用一个而不是另一个?
您使用 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
});
sequelize.define("aModel", {
text: DataTypes.TEXT
}, {
instanceMethods: {
getme1: function() {
return this.text.toUpperCase();
}
},
getterMethods: {
getme2: function() {
return this.text.toUpperCase();
}
}
});
InstanceMethods and getterMethods 似乎完成了同样的事情,允许访问虚拟键。你为什么要用一个而不是另一个?
您使用 Model.method()
调用的实例方法,但是如果您有一个名为 text
的 getter 方法,它将在您执行 instance.text
时被调用。同样,当您执行 instance.text = 'something'
.
示例:
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
});