function Square(a) {
this.a = a ** 2;
return a;
}
const value = Square.call({}, 5);
console.log(value.a);
Actual -> value.a = undefined
Expected -> value.a = 25
CodePudding user response:
You are returning a
, so 5
, not the object. And you pass an object {}
for this
, but it is not stored anywhere, you can't check it later. If you passed an object which you have access to afterwards, like diz
below, its .a
becomes 25 properly:
function Square(a) {
this.a = a ** 2;
return a;
}
const diz = {};
const value = Square.call(diz, 5);
console.log("Returned 'a', should be 5:",value);
console.log("Altered 'object.a', should be 25:",diz.a);
Alternatively you might have wanted to return this;
:
function Square(a) {
this.a = a ** 2;
return this;
}
const value = Square.call({}, 5);
console.log(value.a);
CodePudding user response:
I don't know why you use this
, or where this object value
is coming from. But let me explain. Your argument a
can't be changed directly. You need to assign it to a variable, e.g. result
to change and return it.
return result = a ** 2;
To call the function, you don't use .call
. You simply call it in your console.log()
.
console.log(square(a));
The whole magic of this function you want to write:
function square(a) {
return result = a * a;
}
console.log(square(a));
// expected result is 25
I recommend a course on freeCodeCamp to learn the fundamentals of JavaScript. You can find it here.