Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add properties to prototypes (javascript)

Tags:

javascript

oop

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

like image 705
Marco Maher Avatar asked Apr 01 '26 04:04

Marco Maher


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.

like image 198
Bergi Avatar answered Apr 03 '26 16:04

Bergi


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.
like image 33
Rahul Bhobe Avatar answered Apr 03 '26 17:04

Rahul Bhobe