Why this code returns a NaN?
Why this code returns a NaN?
function m(age)
this.d = second;
function second()
var k = 65 - this.age;
return k;
var asd = new m(20);
document.write(asd.d());
Why this code doesn't print out 45
? I think I did almost same as this YouTube video, but mine doesn't work.
45
Please also explain why I don't need '()' after second here?:
function m(age)
this.d = second;
1 Answer
1
You need to assign the age
parameter passed to the constructor to this.age
so that referencing this.age
refers to it properly later. Otherwise, as in your code, the age
parameter is passed but never used and subsequently discarded:
age
this.age
this.age
age
function m(age)
this.age = age;
this.d = second;
function second()
var k = 65 - this.age;
return k;
var asd = new m(20);
document.write(asd.d());
You might consider using a linter - the no-unused-vars rule would have alerted you to the problem.
It doesn't matter which line runs first in the constructor, because regardless, the constructor will finish running all of its lines before
asd.d()
is called - see how your new m(20)
is above asd.d()
in your code. If you called second
before you assigned to this.age
, it would indeed result in the attempted access of this.age
evaluating to undefined
.– CertainPerformance
Aug 22 at 0:43
asd.d()
new m(20)
asd.d()
second
this.age
this.age
undefined
function m(age) this.d = second; this.age = age;
i meant this, look, i called second and then assigned age parameter to this.age
but it also works– Hydsoled
Aug 22 at 1:21
function m(age) this.d = second; this.age = age;
this.age
You aren't calling second there - as you can see, there are no parentheses. Function invocations require parentheses, like
second()
. All you're doing is assigning this.d
a reference of second
, such that calling .d()
will call second()
(with the new calling context)– CertainPerformance
Aug 22 at 1:37
second()
this.d
second
.d()
second()
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
i got it thank you but, if i swap points this.age = age; and this.d = second; it is correct though, why? when i assign age parameter to 'this.age' after 'this.d = second'
– Hydsoled
Aug 22 at 0:41