Search code examples
javascriptargumentsprototype

Using arguments.length in Object-prototype


I have a person class that has a sub-class of User and Admin and User will create user instances... Now validating my addPerson() properties by checking the arguments.length will not work.

if statement won't get executed even though i can log arguments.length

var Person = function(name, email) {
  this.name = name;
  this.email = email;

  this.addPerson = function(name, email) {
    var paraLength = arguments.length;
    console.log(paraLength) //logs 2
    if(paraLength < 2 || > 2) {
      return "Input must be just name and email"; //does nothing
    }else{
    //do other things
    }
}

const User = function(name, email) {
  Person.call(this, name, email);
  this.addPerson(name, email); //adding user on execution
};

User.prototype = Object.create(Person.prototype);

//Pointing User constructor to itself so it can override properties
User.prototype.constructor = User;
var user1 = new User("user1", "email@gmail", "this error", "not just ignored")

I'd like to terminate on return statement if the parameter passed in are less or more than two. Note: I intend using object prototype


Solution

  • Not really sure what User.addPerson() is supposed to do, but to answer your main question…

    If you want to catch too many (or too few) parameters passed to new User() in the addPerson() function, you could pass on the arguments rather than just the name and email. You can do that with:

    this.addPerson.apply(this, arguments);
    

    to make addPerson see all the arguments passed into User()

    var Person = function(name, email) {
      this.name = name;
      this.email = email;
    
      this.addPerson = function(name, email) {
        var paraLength = arguments.length;
        console.log(paraLength) //logs 2
        if(paraLength < 2 || paraLength > 2) {
          console.log( "Input must be just name and email"); //does nothing
        }else{
        //do other things
        }
    }
    }
    
    const User = function(name, email) {
      Person.call(this, name, email);
      this.addPerson.apply(this, arguments); //adding user on execution
    };
    
    User.prototype = Object.create(Person.prototype);
    
    var user1 = new User("user1", "email@gmail", "this error", "not just ignored")