Kenny Omega
Kenny Omega

Reputation: 398

delete operator does not work with the prototype property

delete operator works with every property except for prototype...

function Foo(name){
    this.name = name;
}

Foo.job = "run";
console.log(Foo.job);//run
console.log(Foo.prototype);//Foo{}

//deleting the properties using the delete operator
console.log(delete Foo.job);//true
console.log(delete Foo.prototype);//false

console.log(Foo.job);//undefined
console.log(Foo.prototype);//Foo{} ???????????????????????

Why does delete operator not work with the prototype property? thanks in advance

Upvotes: 0

Views: 208

Answers (2)

Mark
Mark

Reputation: 92450

If you examine the property descriptor for Foo.prototype you will find it is non-configuarble, which means it can't be deleted:

function Foo(){}

console.log(Object.getOwnPropertyDescriptor(Foo,'prototype'))

Additionally, once a configurable is set to false on a property it cannot be set back to true. So there's no way to delete the prototype from a function. (it's also hard to imagine a use case for do so.)

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370989

Built-in prototype properties are not deletable because they're not a configurable property.

function Foo(name){
    this.name = name;
}

console.log(
  Object
  .getOwnPropertyDescriptor(Foo, 'prototype')
  .configurable
);

Properties added explicitly, such as job in your example, generally are configurable though:

function Foo(name){
    this.name = name;
}
Foo.job = 'run';

console.log(
  Object
  .getOwnPropertyDescriptor(Foo, 'job')
  .configurable
);

Configurable, per MDN:

true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.

You can define properties that aren't configurable if you wish, though, with Object.defineProperty:

function Foo(name){
    this.name = name;
}
Object.defineProperty(
  Foo,
  'job',
  {
    value: 'foo',
    configuable: false
  }
)
delete Foo.job;
console.log(Foo.job);

Upvotes: 1

Related Questions