1

I have an object like this.

var v= {
    a: 1,
    delete: () => delete this.a,
}

I am not able to delete a after executing v.delete

PranavPinarayi
  • 2,044
  • 3
  • 19
  • 25
  • 1
    Also relevant: [Self-references in object literals / initializers](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) – VLAZ Jun 08 '20 at 06:04
  • 2
    For this you need a normal function `delete: function()` or a shorthand method `delete()`. Arrow function will not have `this` equal to the current object but equal to the context wherever that object was created. – VLAZ Jun 08 '20 at 06:06

2 Answers2

2

You need convert arrow to function to use this keyword.

Also you did not call delete method to delete property.

var v= {
    a: 1,
    delete: function () {
      delete this.a
    }
}

v.delete()

console.log(v)
Hien Nguyen
  • 21,001
  • 7
  • 35
  • 48
1

var v= {
    a: 1,
    delete: function(){delete this.a}
}

console.log("before=" + v.a)
v.delete()
console.log("after="v.a)

Arrow function doesn't have access to this context of the current object.

kooskoos
  • 3,670
  • 7
  • 20