getter和setter如何工作?

问题总结:从概念上讲,什么是getter和setter,以及为什么要使用它们?

摘自http://docs.sequelizejs.com/en/latest/docs/models-definition/?highlight=getterMethods#getters-setters :

可以在模型上定义“对象属性”getter和setter函数,这些函数既可用于映射到数据库字段的“保护”属性,也可用于定义“伪”属性。

  1. “保护”是什么意思? 反对什么?

  2. 什么是psuedo属性?

我也在努力处理下面的示例代码。 我们似乎是两次设置“标题”。 v是什么意思?

见下文:

var Foo = sequelize.define('Foo', { title: { type : Sequelize.STRING, allowNull: false, } }, { getterMethods : { title : function() { /* do your magic here and return something! */ }, title_slug : function() { return slugify(this.title); } }, setterMethods : { title : function(v) { /* do your magic with the input here! */ }, } }); 

一个具体的例子,而不是“做魔术”将不胜感激!

伪属性

会是属性,从用户的angular度来看似乎是对象的常规属性,但不存在于数据库中。 以一个具有名字和姓氏字段的用户对象为例。 然后你可以创build一个全名设置器:

 var foo = sequelize.define('foo', { .. }, { getterMethods: { fullName: function () { return this.getDataValue('firstName') + ' ' + this.getDataValue('lastName') } }, setterMethods: { fullName: function (value) { var parts = value.split(' ') this.setDataValue('lastName', parts[parts.length-1]) this.setDataValue('firstName', parts[0]) // this of course does not work if the user has several first names } } }) 

当你有一个用户对象,你可以简单地做

 console.log(user.fullName) 

查看用户的全名。 然后在幕后调用getter。

类似的,如果你为全名定义一个setter方法,你可以这样做

 user.fullName = 'John Doe' 

然后,它将把传入的string分成两部分并保存在名字和姓氏中。 (见上面的简单例子)

保护属性

@ahiipsa已经提供了一个很好的例子。 当您执行user.toJSON()时会调用Getters,因此您可以使用getters轻松删除敏感数据,然后将其发送给用户。