getter不能在JavaScript中工作
我试图找出JavaScript中的getter和setter是什么。 这是我的目标getter不能在JavaScript中工作,javascript,getter-setter,Javascript,Getter Setter,我试图找出JavaScript中的getter和setter是什么。 这是我的目标 function User(fullName) { this.fullName = fullName; Object.defineProperties(this,{ firstName :{ get: function(){ return this.fullName.split(
function User(fullName) {
this.fullName = fullName;
Object.defineProperties(this,{
firstName :{
get: function(){
return this.fullName.split(" ")[0];
},
set :function(value){
this.firstName = value;
}
},
lastName:{
get: function(){
this.lastName = this.fullName.split(" ")[1];
},
set: function(value){
this.lastName = value;
}
},
fullName :{
set: function(value){
this.fullName = value;
}
}
});
}
然后创建一个新用户:
var user=新用户(“新用户”)代码>
但是当我想得到第一个名字的时候
警报(user.firstName)
它抛出一个错误“无法读取未定义的属性'split'
什么可能导致问题?看起来“this”在get函数中是不可见的,但据我所知,它应该是可见的。谢谢 fullName没有getter,因此返回undefined
获取
用作属性的getter的函数,如果没有getter,则为未定义的函数。函数return将用作属性的值
默认为未定义的
您不需要设置全名的setter,因为直接分配将起作用
函数用户(全名){
this.fullName=fullName | |“”;
对象。定义属性(此{
名字:{
get:function(){
返回此.fullName.split(“”[0];
},
设置:函数(值){
this.firstName=value;//注意:这将引发一个错误
}
},
姓氏:{
get:function(){
返回此.fullName.split(“”[1];
},
设置:函数(值){
this.lastName=value;//注意:这将引发一个错误
}
}
});
}
var joe=新用户('John Doe');
var jane=新用户(“jane Dane”);
jane.fullName='jane Doe';
document.write(
''+joe.firstName+''的名字+
''+jane.lastName+''的
);代码>需要对代码进行的一些问题/更改:
this.fullName.split(“”[0];=>将尝试调用getFullName,因为fullName定义为属性。由于尚未定义getFullName,因此会导致错误
假设您继续为fullName定义一个getter:
get:function(){
返回this.fullName;
}
这将引发stackoverflow,因为This.fullName以递归方式调用getFullName()结束
使用它的正确方法是(当然,更新setter来做一些有用的事情):
函数用户(全名){
this.fullName=fullName;
对象。定义属性(此{
名字:{
get:function(){
返回此.fullName.split(“”[0];
},
设置:函数(值){
this.firstName=值;
}
},
姓氏:{
get:function(){
返回此.fullName.split(“”[1];
},
设置:函数(值){
this.lastName=值;
}
}
});
}
var user=新用户(“新用户”);
警报(user.firstName)代码>检查代码中引用的内容。设置firstName
或lastName
仍会引发错误:user.firstName='Foo'代码>