Javascript BrainStorming | Output Questions
Here are the answers and explanations to the JavaScript questions:
1. Method vs. Regular Function Call
const obj = {
a: 10,
getA() {
return this.a;
},
getB: function() {
return this.a;
}
};
const test1 = obj.getA;
const test2 = obj.getB;
console.log(obj.getA()); // 10
console.log(test1()); // undefined
console.log(obj.getB()); // 10
console.log(test2()); // undefined
2. Arrow Function vs. Regular Function
const obj = {
a: 5,
regularFn: function() {
return this.a;
},
arrowFn: () => {
return this.a;
}
};
console.log(obj.regularFn()); // 5
console.log(obj.arrowFn()); // undefined
3. Function Inside Method
const obj = {
a: 42,
getA() {
function innerFn() {
return this.a;
}
return innerFn();
}
};
console.log(obj.getA()); // undefined
4 .Using bind()
const obj = {
a: 7,
getA() {
return this.a;
}
};
const test = obj.getA.bind({ a: 20 });
console.log(obj.getA()); // 7
console.log(test()); // 20
领英推荐
5. Changing this with call() and apply()
const obj = {
a: 3,
getA() {
return this.a;
}
};
const anotherObj = { a: 99 };
console.log(obj.getA()); // 3
console.log(obj.getA.call(anotherObj)); // 99
console.log(obj.getA.apply(anotherObj)); // 99
6. this in Callback Functions
const obj = {
a: 8,
getA() {
setTimeout(function() {
console.log(this.a);
}, 100);
}
};
obj.getA(); // undefined
7. Arrow Function as a Constructor
const MyClass = () => {
this.a = 10;
};
const instance = new MyClass();
console.log(instance.a); // TypeError: MyClass is not a constructor
8. this in a Class
class MyClass {
constructor() {
this.a = 50;
}
getA() {
return this.a;
}
static getStaticA() {
return this.a;
}
}
const instance = new MyClass();
console.log(instance.getA()); // 50
console.log(MyClass.getStaticA()); // undefined