How to add properties to prototypes (javascript)

Viewed 102

The following function Phone() creates a prototype and Phone.prototype.screenSize = 6; adds the screenSize property

function Phone() {
  this.operatingSystem = 'Android';
}

Phone.prototype.screenSize = 6;

then if we made a new object myPhone and checked if it contains the screenSize property it returns false although the property was added before creating the object.

const myPhone = new Phone();

const inherited = myPhone.hasOwnProperty('screenSize');

console.log(inherited);
// false

Why doesn't it return true and how to make it return true

2 Answers

Why doesn't hasOwnProperty return true?

Because it's not an own property of myPhone, it's inherited from the prototype object.

how to check the prototype chain?

Use the in operator instead.

Adding a property type to prototype will only add the "own" property to prototype and not the instance.

Phone.prototype.screenSize = 6;
Phone.prototype.hasOwnProperty('screenSize'); // true


const myPhone = new Phone();
myPhone.hasOwnProperty('screenSize'); // false
// instances will not own the property.
Related