Javascript Setter未设置其他属性值

时间:2017-03-08 22:37:01

标签: javascript

我正在使用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参数传入的内容返回正确的值。

我也尝试以与PasswordHash相同的方式实现PasswordValue(即使用getter / setter和支持成员),但这会返回相同的结果。

我错过了什么?

注意:这显然不是生产代码,我只是在探索以前没用过的JS的一些方面!

1 个答案:

答案 0 :(得分:2)

您需要在this内拨打Object.defineProperty(User, "Password",。我修改了你的代码,它现在正在工作。

&#13;
&#13;
'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);
&#13;
&#13;
&#13;