0

I am trying to solve a problem where I have the following piece of code:

var piggie = new Animal(Animal.PIG);

How can a Constructor function (new Animal) also be an Object with properties (Animal.PIG)?

I have tried this solution:

function Animal(type) {
    this.typeOf = type;

    return {
        PIG: 'Pig'   
    };
}

But Animal.PIG is undefined? JS Fiddle is here: http://jsfiddle.net/bufr2b4c/

4
  • You cannot return something from a constructor, when called with new, it returns the newly constructed object, this Commented Apr 22, 2015 at 15:48
  • this is not the way, just go to MDN in google and read litle bit, you do not need SO for this. Commented Apr 22, 2015 at 15:49
  • 1
    @JuanMendes — You can, it's just a terrible idea and it returns what you say instead of this which makes using a constructor function pointless. Commented Apr 23, 2015 at 8:55
  • @Quentin I'll be darned jsfiddle.net/mendesjuan/cercykLb I knew I should have tested before saying so, I thought I had heard something about that. Commented Apr 23, 2015 at 9:29

2 Answers 2

1

For Animal.PIG to have a value, you have to create a property on the constructor function itself.

function Animal(type) {
    this.typeOf = type;
}

Animal.PIG = "Pig";

Your code is creating an object when the constructor runs and setting PIG on that object. (And discarding the constructed Animal instance as you go).

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

Comments

0

You ned execute console.log((new Animal).PIG); //It's done! because you are accessing to a property of an object (you need create this object. Therefore you needs to use NEW)

function Animal(type) {
    this.typeOf = type;

    return {
        PIG: 'Pig'   
    };
}

console.log(new Animal);
console.log((new Animal).PIG); //this is undefined, but why?

console.log(typeof Animal);             // "function"
console.log(Animal instanceof Object);  // true

EDITED

You can use something like below:

function Color(col) {   
   this.color = col;
   this.getColor = function() {
       return this.color;
   }
}

var blueBox = new Color("blue");
alert(blueBox.getColor()); // will alert blue
alert(blueBox.color); // will alert blue

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.