xxxxxxxxxx
//Constructor function is function that generate object.
//capital function name indicate it is constructor function
function Todo(name, completed) {
console.log(this); //return empty object name todo
this.name = name;
this.completed = completed;
this.getTodoName = function () {
console.log(this.name);
};
}
//new keyword do two things
//create new empty object
//and assign this with that object.
const todo = new Todo('Get Eggs', false);
console.log(todo); //log return object
todo.getTodoName(); //logo Get Eggs
xxxxxxxxxx
//Constructor Function
function BellBoy (name, age, hasWorkPermit, languages) {
this.name = name;
this.age = age;
this.hasWorkPermit = hasWorkPermit;
this.languages = languages;
}
//Create New Object From Constructor Using Arguments
var Earl = new BellBoy('Earl E.Bird', 23, true, ['French', 'German'])
//Access the Properties and Their Values
console.log('Name : ', Earl.name)
console.log('Age : ', Earl.age)
console.log('Verified Work Permit : ', Earl.hasWorkPermit)
console.log('Languages : ', Earl.languages)
xxxxxxxxxx
// Constructors in JavaScript
// Constructor function
function Person(name, age) {
this.name = name;
this.age = age;
}
// Creating instances using the constructor
const person1 = new Person("John", 25);
const person2 = new Person("Jane", 30);
console.log(person1); // Output: Person { name: 'John', age: 25 }
console.log(person2); // Output: Person { name: 'Jane', age: 30 }
xxxxxxxxxx
var MyConstructor = function(p1, p2, p3){
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
};
xxxxxxxxxx
// The function constructor can take in multiple statements separated by a semicolon. Function expressions require a return statement with the function's name
// Observe that new Function is called. This is so we can call the function we created directly afterwards
const sumOfArray = new Function('const sumArray = (arr) => arr.reduce((previousValue, currentValue) => previousValue + currentValue); return sumArray')();
// call the function
sumOfArray([1, 2, 3, 4]);
// 10
// If you don't call new Function at the point of creation, you can use the Function.call() method to call it
const findLargestNumber = new Function('function findLargestNumber (arr) { return Math.max(...arr) }; return findLargestNumber');
// call the function
findLargestNumber.call({}).call({}, [2, 4, 1, 8, 5]);
// 8
// Function declarations do not require a return statement
const sayHello = new Function('return function (name) { return `Hello, ${name}` }')();
// call the function
sayHello('world');
// Hello, world