0
Follow
0
View

I don't know why this 'this' method doesn't work?

drumying 注册会员
2023-01-25 20:52

You are storing a function, not calling it that's why it should print you undefined. To fix it you should call it with list.calcAge().

Your code works and this.age = 2002 - this.birthYear creates the property you want, you just need to call it before using it.

const list = {
    name: 'Harry Potter',
    birthYear: 1995,

    calcAge: function () {
        this.age = 2002 - this.birthYear;
        return this.age;
    }
};
list.calcAge()
console.log(list.age);
lwaooo0777 注册会员
2023-01-25 20:52

Try this. It will work.

const list = {
    name: 'Harry Potter',
    birthYear: 1995,

    calcAge: function () {
        this.age = 2002 - this.birthYear;
        return this.age;
    },
};

console.log(list.calcAge());

Try calling list.calcAge() in your console

deathcj 注册会员
2023-01-25 20:52

the calcAge is function property so you must be treated as a function list.calcAge()

const list = {
name: 'Harry Potter',
birthYear: 1995,
calcAge: function () {
  this.age = 2002 - this.birthYear;
  return this.age;
    }
};
document.getElementById("name").innerHTML = list.name;
document.getElementById("birthYear").innerHTML = list.birthYear;
document.getElementById("age").innerHTML = list.calcAge();


    
        
    
    
        

dwj313 注册会员
2023-01-25 20:52

Call your function. list.calcAge() You can print it like this console.log(list.calcAge()) You were close though!!

dandan1980 注册会员
2023-01-25 20:52

const list = {
    name: 'Harry Potter',
    birthYear: 1995,

    calcAge() {
        this.age = 2002 - this.birthYear;
        return this.age;
    },
};

console.log(list.calcAge());