function person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
person.prototype.getfullName = function() {
return `${this.firstName} ${this.lastName}`
}
}
function person2(firstName, lastName, age, location) {
person.call(firstName, lastName)
this.age = age;
this.location = location;
}
person2.prototype = new person()
let result = new person2('nivedhan', 'kumar', 24, 'neyveli')
console.log(result.getfullName())
console.log(result.age)
Error: I'm getting error stating that
'Cannot create property 'firstName' on string 'nivedhan'
CodePudding user response:
There are a couple of issues here:
person2.prototype = new person()
is wrong way of inheritance ( More on that here )
It should be
person2.prototype = Object.create(person.prototype);
person2.prototype.constructor = person2;
person.prototype.getfullName
should be declared outside of person
constructor function. Otherwise, every instance created using new
will update the method on the prototype
(Reference: here, here and here)
function person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
person.prototype.getfullName = function() {
return `${this.firstName} ${this.lastName}`
}
The first argument to the .call
is the this
value to be used inside the person
function. So, it should be
person.call(this, firstName, lastName)
Here's the updated snippet:
function person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
person.prototype.getfullName = function() {
return `${this.firstName} ${this.lastName}`
}
function person2(firstName, lastName, age, location) {
person.call(this, firstName, lastName)
this.age = age;
this.location = location;
}
person2.prototype = Object.create(person.prototype);
person2.prototype.constructor = person2;
let result = new person2('nivedhan', 'kumar', 24, 'neyveli')
console.log(result.getfullName())
console.log(result.age)
CodePudding user response:
call allows us to manually and explicitly set the this keyword of any function we want to call. call() provides a new value of this to the function/method. With call() we can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
const user = {
name: 'john',
setName: function(name) {
this.name = name;
},
getName: function() {
return this.name;
}
}
const user2 = {
name: 'sam'
}
const getName = user.getName;
const name = getName.call(user2); //return john
console.log(name)