We have discussed 2 ways of creating object blueprints which are constructor functions and ES6 classes, but there still 1 less popular way of doing so which is the Object.create() method
Creating objects with object.create()
first, the method takes 1 required paramater and another optional param, the first is the prototype to assign to the newly created object and the other is the props of the object
Example
let's recreate the Customer blueprint
const CustomerProto = {
name: "",
email: "",
password: "",
settings: {},
cart: [],
setSettings: function (settings) {
this.settings = settings;
},
orderFood: function (food) {
console.log(`ordering ${food}`);
},
};
const customer = Object.create(CustomerProto);
customer.name = "name";
customer.email = "email";
customer.password = "password";
customer.setSettings({});
customer.cart = [];
customer.orderFood("pizza");
the methods declared in the CustomerProto oject will be applied to the new object automatically
as you can see this approach takes more code to work than other methods
in the next post i will talk about the principles of object oriented programming
Top comments (0)