Which code should you use?

You are creating a custom object as described by the following code.

You need to implement the calcArea method.
Which code should you use?

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



Leave a Reply 5

Your email address will not be published. Required fields are marked *


Valikhan

Valikhan

I think the correct answer is B, coz in option D keyword ‘this’ will point to global object (window)

Ivan

Ivan

It can’t be the option B, because the calcArea function is calling (this.area = calcArea;) without arguments. The correct answer is D.

rik

rik

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.

stijn

stijn

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

debbie

debbie

True, answer D is correct