xxxxxxxxxx
const o = {};
o.constructor === Object;
xxxxxxxxxx
/* A constructor in Javascript is used to create a new object and set values
for any existing object properties*/
class Animal{
constructor (name, height, weight){
console.log("created animal named", name)
}
nameLength() {
return name.length;
}
}
var dog = new Animal("Fido", 25, 90);
var fish = new Animal("Goldie", 2, .02);
console.log(dog.nameLength);
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
var MyConstructor = function(p1, p2, p3){
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
};
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
// 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