I can't find a set of google search terms that answer this question. Is there a javascript equivalent to PHP's __construct function, ie 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();
You can use constructor() inside javascript classes for the same use.
Sample:
class Car {
constructor(brand) { // Constructor
this.carname = brand;
}
}
mycar = new Car("Ford");
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.