0

Let's say I have an object life:

var life = {
    name: "John Doe",
    age: 45
};

And I call a method die 5 seconds after my webpage loads:

setTimeout(life.die, 5000);

var life = {
    name: "John Doe",
    age: 45,
    die: function() {
        //Die
    }   
};      

How would I create a property dead from within the method die? Is it as simple as this?

die: function() {
    this.dead = true;
}

Or this?

die: function() {
    var this.dead = true;
}    

Or do I need to use something else?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79

1 Answers1

1

You can the use the variable name life and assign property dead internally in the function scope it will assign to the life object automatically. If you are using this means it will assign to window object.

     
    
     var life = {
            name: "John Doe",
            age: 45,
            die:  () => {
                life.dead = true;
                console.log(life)
            }
        };
        
        setTimeout(life.die, 5000);