1

Oke, I have this working:

const personProto2 = {
  calAge() {
    console.log(2021 - this.birthday);
  },
};
const rein = Object.create(personProto2);
rein.name = "Rein";
rein.birthday = 1945;
rein.calAge();

But if I do this:

const Person = function (name, birthday) {
  this.name = name;
  this.birthday = birthday;
};

Person.prototype.calAge = function () {
  console.log(2021 - this.birthday);
};
const rein = Object.create(Person);
rein.name = "Rein";
rein.birthday = 1945;
rein.prototype.calAge();

It doesn't work. But a function is also a object. And a object has also a prototype.

So why the second example doesn't work?

1 Answer 1

1

I think that you meant using new when creating a blank, plain JavaScript object.

The new operator lets you create an instance of a user-defined object type or of one of the built-in object types that has a constructor function. now, you can call the calAge method.

function Person(name, birthday) {
  this.name = name;
  this.birthday = birthday;
};

Person.prototype.calAge = function () {
  console.log(2021 - this.birthday);
};

const rein = new Person("Rein", 1945);
rein.calAge();

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

1 Comment

Thank you. Ah, oke. So a function is an object. But function name(){} doens't create a object with Object.create. And {} with Object.create createds an object.

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.