0

When I used getFullName, getFirstName and getLastName work ok, but I can't use set functions setFullName, setLastName, setFirstName. My code:

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(' ');};

};
1
  • You're setting fn[0], not frn Commented Mar 6, 2016 at 11:19

1 Answer 1

1

What about this:

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];};
};

See this fiddle

If you have a lot of Person objects, you should consider moving the getter/setter functions to the 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];
}

See updated fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.