3

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

8
  • 1
    "Why doesn't it return true" hasOwnProperty checks the object and explicitly not the prototype chain. Commented Jun 23, 2020 at 16:22
  • how to check the prototype chain? Commented Jun 23, 2020 at 16:23
  • 1
    It's not a property of the new object, it's a property of its prototype. Commented Jun 23, 2020 at 16:23
  • 2
    "how to make it return true" what is your goal? Do you want to make sure hasOwnProperty returns true? Then you need to attach the property to the instance. Do you want to verify the property exists? Then use in. This seems a bit like an XY problem Commented Jun 23, 2020 at 16:24
  • + didn't the screenSize became part of the chain just like operatingSystem? @VLAZ Commented Jun 23, 2020 at 16:25

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.