You are creating a custom object as described by the following code.
You need to implement the calcArea method. Which code should you use?
A. Option A
B. Option B
C. Option C
D. Option D
5 Comments on “Which code should you use?”
Valikhansays:
I think the correct answer is B, coz in option D keyword ‘this’ will point to global object (window)
0
0
Ivansays:
It can’t be the option B, because the calcArea function is calling (this.area = calcArea;) without arguments. The correct answer is D.
1
0
riksays:
Seems to me you are both right.
Using ‘this’ inside a function that is used as a parameter for a function will make said ‘this’ point to the window object.
As a workaround, the ‘this’ can be assigned to a variable (‘that’) which is then used as a parameter. So, if “var that = this;” was added to the square() function it should work like so:
function square(side){
this.side = side;
var that = this;
this.area = calcArea(that);
}
function calcArea(obj){
return obj.side * obj.side;
}
So the way I see it, either answers A, B, C and D are all wrong or the question is incomplete.
0
0
stijnsays:
answer D is correct
function square(side) {
this.side = side;
this.area = calcArea;
}
function calcArea() {
return this.side * this.side;
}
var square = new square(10);
console.log(square.area()); //result 100
I think the correct answer is B, coz in option D keyword ‘this’ will point to global object (window)
0
0
It can’t be the option B, because the calcArea function is calling (this.area = calcArea;) without arguments. The correct answer is D.
1
0
Seems to me you are both right.
Using ‘this’ inside a function that is used as a parameter for a function will make said ‘this’ point to the window object.
As a workaround, the ‘this’ can be assigned to a variable (‘that’) which is then used as a parameter. So, if “var that = this;” was added to the square() function it should work like so:
function square(side){
this.side = side;
var that = this;
this.area = calcArea(that);
}
function calcArea(obj){
return obj.side * obj.side;
}
So the way I see it, either answers A, B, C and D are all wrong or the question is incomplete.
0
0
answer D is correct
function square(side) {
this.side = side;
this.area = calcArea;
}
function calcArea() {
return this.side * this.side;
}
var square = new square(10);
console.log(square.area()); //result 100
1
0
True, answer D is correct
1
0