我正在玩 Javascript getter 和 setter,我似乎无法从 setter 中设置附加属性的值:
'use strict';
var lastUserId = 0;
function getNewUserId()
{
var id = lastUserId;
lastUserId++;
return id;
}
function User(_name, _email, _password)
{
this.Name = _name;
this.Email = _email;
this.Id = getNewUserId();
//Make the Id read-only
Object.defineProperty(this, 'Id', {writable: false});
//Test changing the Id - Should get a read-only error.
//this.Id = 12;
this.PasswordHash = -1; //Inital value
var PasswordValue;
Object.defineProperty(User, "Password",
{
configurable: true,
get: function() {
return this.PasswordValue;
},
set : function(value) {
this.PasswordHash = hashCode(value);
this.PasswordValue = value;
}
});
this.Password = _password;
//this.PasswordHash = "thisWorks";
}
function hashCode (val) {
var hash = 0, i, chr, len;
if (val.length === 0) return hash;
for (i = 0, len = val.length; i < len; i++) {
chr = val.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
当我创建 User
对象的新实例时,我希望通过 PasswordValue setter 设置 PasswordHash,但是在实例化后检查 PasswordHash 的值返回 -1
(属性的初始值)。 - 根据我作为 _password
参数传入的内容,检查 Password
的值返回正确的值。
我也尝试过以与 PasswordValue
相同的方式实现 PasswordHash
(即使用 getter/setter 和支持成员),但这会返回相同的结果。
我错过了什么?
注意:这显然不是生产代码,我只是在探索我以前没有使用过的 JS 的一些领域!
最佳答案
您需要在 Object.defineProperty(User, "Password",
) 中调用 this
。我稍微修改了您的代码,现在可以使用了。
'use strict';
var lastUserId = 0;
function getNewUserId()
{
var id = lastUserId;
lastUserId++;
return id;
}
var User = function(_name, _email, _password) {
this.Name = _name;
this.Email = _email;
this.Id = getNewUserId();
//Make the Id read-only
Object.defineProperty(this, 'Id', {writable: false});
Object.defineProperty(this, "Password", {
configurable: true,
get: function() {
return this.PasswordValue;
},
set : function(value) {
this.PasswordHash = hashCode(value);
this.PasswordValue = value;
}
});
this.Password = _password;
}
function hashCode (val) {
var hash = 0, i, chr, len;
if (val.length === 0) return hash;
for (i = 0, len = val.length; i < len; i++) {
chr = val.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var u = new User("Fan", "test@email.com", "123456");
console.log(u.PasswordHash);
关于Javascript Setter 没有设置额外的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42683250/