0

I can't find a set of google search terms that answer this question. Is there a javascript equivalent to PHP's __construct function, i.e. a function that runs automatically whenever the object is instantiated?

var pizza = {
    var crust,
    ** instantiate? **: function(){
        this.crust = true;
    },
    topping: function(myTopping){
        this.crust += myTopping;
    },
    bake: function(){
        alert('done!');
    }
}

var mypizza = new pizza(); // << crust is added right away, internally
mypizza.topping('pepperoni');
mypizza.topping('green pepper');
mypizza.topping('onion');
mypizza.bake();
3
  • 1
    Have you tried to run your code? You can't call an object like that, or declare variables inside an object literal. Commented Apr 14, 2020 at 17:04
  • Not this code, no. It's just a tossoff to ask the question. Commented Apr 14, 2020 at 18:56
  • Well, we expect examples being syntactically valid too ... Commented Apr 14, 2020 at 18:57

2 Answers 2

1

You can use constructor() inside javascript classes for the same use.

Sample:

class Car {
  constructor(brand) {  // Constructor
    this.carname = brand;
  }
}
mycar = new Car("Ford");
Sign up to request clarification or add additional context in comments.

Comments

1

You can do something like this -

class Pizza {
  constructor() {
    this.crust = true;
  }
}

const pizza = new Pizza();

More information on constructor is available here for your reading

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor

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.