Загрузка...

Part 23 | JavaScript Tutorial | Creating objects in JS | Function Constructor | Object Create metho

Content:- An object can be created mainly in 4 ways: 1. Literal way - Using {} we can create an object. eg: let a = {name: "Trinits"}; 2. Using new keywords. const person = new Object(); person.name = "Trinits"; Note:- For readability, simplicity, and execution speed, use the object literal method. 3. Using Function constructor:- - creating an object using a constructor function. The new keyword is used to create a new instance of the object. - good practice to name constructor functions with an upper-case first letter. - Note:- Using the arrow functions, we can't create the Function constructor. function Person(name, age) { this.name = name; this.age = age; this.getName = function() { return "MR/MS" + this.name; }; } const p1 = new Person("Trinits", 20); const p1 = new Person("Technologies", 25); - We can add a method to the existing object as given below p1.getName = function () { return "MR/MS" + this.name; }; - We can add the additional properties as given below p1.salary = 50000; 4. Object.create() - Create an object with an existing object as a prototype let a = Object.create(null) a.name ="Trinits"; //Creating object based on another one. const myPrototype = { prop1: value1, prop2: value2, }; const myObject = Object.create(myPrototype); 5. ES6 Class syntax: This involves defining a class with a constructor and any other methods on the class. class Person { constructor(prop1, prop2) { this.prop1 = prop1; this.prop2 = prop2; } myMethod() { // method code here } } const myObject = new Person(value1, value2);

Видео Part 23 | JavaScript Tutorial | Creating objects in JS | Function Constructor | Object Create metho автора Доход с Программирования на JS
Страницу в закладки Мои закладки
Все заметки Новая заметка Страницу в заметки