을 설정하지 않는 내가 세터 내부에서 추가 속성 값을 설정할 수없는 것 : 나는 새를 만들 때자바 스크립트 세터 추가 속성 값
'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
개체의 PasswordHash가 PasswordHue setter를 통해 설정되지만, 인스턴스화 후 PasswordHash 값을 확인하면 -1
(속성의 초기 값)이 반환됩니다. - Password
의 값을 확인하면 _password
매개 변수로 전달 된 값을 기반으로 올바른 값이 반환됩니다.
PasswordValue
(예 : getter/setter 및지지 멤버)과 같은 방식으로 PasswordHash
을 구현하려고했지만 동일한 결과가 반환됩니다.
무엇이 누락 되었습니까?
참고 : 이것은 분명히 프로덕션 코드가 아니며 이전에 사용하지 않은 JS의 일부 영역을 탐색 중입니다!
@AndrewLi - 내가하고 있어요'Password'은'_password' 매개 변수의 값 (오른쪽 끝) 생성자 내부. – KidCode