John Abraham
John Abraham

Reputation: 18811

How to properly return values when using 'this' in an 'constructor' and the prototype methods of the object?

For live code sample checkout my: Codepen

Question: How can I make sure that p1.prototype.setFirst() & p1.prototype.fullName() return the proper values while still using this?

var Person = function(){
     this.firstName = "Penelope";
     this.lastName = "Barrymore";

}
Person.prototype.fullName = function () {
  return this.firstName + " " + this.lastName;
}
Person.prototype.setFirst = function () {
  return this.firstName = "mark"
}
var p1 = new Person();
p1.prototype.setFirst()
console.log(p1.prototype.fullName());

Upvotes: 0

Views: 27

Answers (1)

Jacob
Jacob

Reputation: 78900

If you really have to call via the prototype like that, you can do:

Person.prototype.setFirst.call(p1);

...and:

Person.prototype.fullName.call(p1);

call and apply are the easiest ways to change this.

If you want reference to a version of a function where this is bound to it, use bind:

var myFullName = Person.prototype.fullName.bind(p1);
myFullName(); // this will be p1

...but of course, this is the natural thing to do:

p1.fullName()

And if you want to get the prototype through the object, you can use:

p1.__proto__

...or:

p1.constructor.prototype

Upvotes: 2

Related Questions