06 - Constructor Function and Binding in JS


const person = {
    
    name: "Sidharth",
    age: 24,
    sayHello: function () {
console.log(`Hello Every One, I\'m ${this.name}. I\'m ${this.age} years old.`);
    }
}

function Person(name,age) { //constructor function
    this.name = name;
    this.age = age;
    // this.sayHello = function () {
    //     console.log(`Hello from ${this.name}`);
    // }
}

Person.prototype.sayHello=function () {
    console.log(`Hello from ${this.name}`);
}


let p1 = new Person("Sidharth", 25);
console.log('p1 = \n');
console.log(p1);
let p2 = new Person("Sid", 24);
console.log('p2 = \n');
console.log(p2);

// OUTPUT:
// p1 = 
// Person {name: "Sidharth", age: 25}
// p2 = 
// Person {name: "Sid", age: 24}

console.log('\n\n');


//--------------------------------------------------------


//BINDING: Implicit and Explicit
//===============================

// Implicit Binding
//===================

const obj = {
    name: "Audi",
    price: 10000,
    getCarDetails: function () {
console.log(this);
    }
}

console.log(obj.getCarDetails()); //here, getCarDetails function binded to the Object obj 
// OUTPUT:
// {name: "Audi", price: 10000, getCarDetails: ƒ}

console.log('\n\n');

// Explicit Binding: with call(), bind(), apply()
//==================================================
function fun(name,age) {
    console.log(this);
    console.log(name);
    console.log(age)
}

const a = {
    l: 10,
    m: 20,
    k: true
}

//01 - with call()
fun.call(a, "Sid", 24);
// OUTPUT:
// {l: 10, m: 20, k: true}
// Sid
// 24

console.log('\n\n');

//02 - with bind()
let f = fun.bind(a);
f("Ram", 21);
// OUTPUT:
// {l: 10, m: 20, k: true}
// Ram
// 21

console.log('\n\n');

//03 - with apply()
fun.apply(a, ["Rahim",21]);
// OUTPUT:
// {l: 10, m: 20, k: true}
// Rahim
// 21

//Note: Read more about Binding here