mightycode Newton
mightycode Newton

Reputation: 3949

Object.Create calling function with prototype

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?

Upvotes: 1

Views: 40

Answers (1)

Ran Turner
Ran Turner

Reputation: 18016

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();

Upvotes: 1

Related Questions