gpt4 book ai didi

javascript - 使用函数将值设置到对象中(javascript)

转载 作者:行者123 更新时间:2023-12-03 07:30:16 24 4
gpt4 key购买 nike

当我使用 getFullName、getFirstName 和 getLastName 时工作正常,但我无法使用设置函数 setFullName、setLastName、setFirstName。我的代码:

var Person = function(firstAndLast) {
var fn=firstAndLast.split(' ');
var fstr=fn.join(' ');
var frn=fn[0];
var lsn=fn[1];

this.getFullName=function(){return fstr;};
this.getFirstName=function(){return frn;};
this.getLastName=function(){return lsn;};
this.setFirstName=function(a){fn[0]=a;};
this.setLastName=function(b){fn[1]=b;};
this.setFullName=function(c){fn=c.split(' ');};

};

最佳答案

这个怎么样:

var Person = function(firstAndLast) {
var self = this;
this.fn = firstAndLast.split(' ');
this.frn = this.fn[0];
this.lsn = this.fn[1];

this.getFullName=function(){return self.fn.join(' ');};
this.getFirstName=function(){return self.frn;};
this.getLastName=function(){return self.lsn;};
this.setFirstName=function(a){self.frn=a; self.fn[0]=a;};
this.setLastName=function(b){self.lsn=b; self.fn[1]=b;};
this.setFullName=function(c){
self.fn = c.split(' ');
self.frn = this.fn[0];
self.lsn = this.fn[1];};
};

参见this fiddle

如果您有很多 Person 对象,则应考虑将 getter/setter 函数移至 class prototype :

var Person = function(firstAndLast) {
this.fn = firstAndLast.split(' ');
this.frn = this.fn[0];
this.lsn = this.fn[1];
};

Person.prototype.getFullName = function() {
return this.fn.join(' ');
}

Person.prototype.getFirstName = function() {
return this.lsn;
}

Person.prototype.getLastName = function() {
return this.lsn;
}

Person.prototype.setFirstName = function(a) {
this.frn=a;
this.fn[0]=a;
}

Person.prototype.setLastName = function(b) {
this.lsn=b;
this.fn[1]=b;
}

Person.prototype.setFullName = function(c) {
this.fn = c.split(' ');
this.frn = this.fn[0];
this.lsn = this.fn[1];
}

参见updated fiddle

关于javascript - 使用函数将值设置到对象中(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35826168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com