0

I am working on a Javascript object exercise. My output is not what I expected. Please take a look at my code and give some advise. Here is the code:

function myFunction(name) {
  this.name = name;
  this.models = new Array();
  this.add = function (brand){ 
    this.models =  brand;
  };
}
var c = new myFunction ("pc");
c.add("HP");
c.add("DELL");
console.log(c.models);

The output is "DELL"

My expected output is ["HP","DELL"]

Thank you so much for your help!

1
  • 2
    a multiple argument version: this.add=[].push.bind(this.models); Commented Mar 27, 2015 at 5:00

2 Answers 2

3

Change the add function. You want to push the brand into the model. Not set the model to it.

this.add = function (brand){ 
    this.models.push(brand);
};
Sign up to request clarification or add additional context in comments.

Comments

1

To add something to an array, you should use the .push() method.

Change your code to:

function myFunction(name) {
  this.name = name;
  this.models = new Array();
  this.add = function (brand){ 
    this.models.push(brand);
  };
}

P.S. It is customary to name such constructor type of functions starting with a capital letter.

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.