I was asked following questionin the interview.
function test1() {
console.log(this);
}
test1();
"use strict";
function test2() {
console.log(this);
}
test2();Answer :
window
this
function introduce(city, country) {
console.log(`${this.name} is ${this.age} years old from ${city}, ${country}`);
}
const person = { name: "ABC", age: 20 };
Answer :
introduce.call(person, "Bangalore", "India");
const boundIntro = introduce.bind(person, "Bangalore", "India");
boundIntro();function Person(name) {
this.name = name;
}
const sayHello = function() {
console.log(`Hello, I am ${this.name}`);
};
const p1 = new Person("Arjun");
p1.sayHello(); // calling sayHello from objectAnswer : I was not able to answer the question.
Person.prototype.sayHello = function() {
console.log(`Hello, I am ${this.name}`);
};
Answer : I was able to implement with little bit of help.
Array.prototype.customReduce = function(cb, init) {
let acc = init === undefined ? this[0] : init;
let i = init === undefined ? 1 : 0;
for (; i < this.length; i++) {
acc = cb(acc, this[i], i, this);
}
return acc;
};
[1, 2, 3, 4].customReduce((a, b) => a + b, 0);Final Verdict : not selected.