Reputation: 59
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.
Please also explain why I don't need '()' after second here?:
function m(age) {
this.d = second;
}
Upvotes: 1
Views: 78
Reputation: 370679
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:
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.
Upvotes: 3