I have gone in an interview yesterday where interviewer asked me about partial inheritance, about which I am clueless. I have mentioned 2 code blocks below as per my understanding. Let me know whatever I am doing is correct or not for partial inheritance.
Code Block 1: Can we call this partial inheritance?
var Person = function(){}
Person.prototype.getName = function(){
return this.name;
}
Person.prototype.setName = function(name){
this.name = name;
}
var Author = function(name, books){
this.books = books;
Person.prototype.setName.call(this, name); <<---- Is this a way of doing partial inheritance?
}
Author.prototype.getBooks = function(){
return this.books;
}
var author = new Author('Auth1', ['b1','b2']);
Code Block 2: How to inherit only "setName" function from "Person" constructor? Is it possible?
var Person = function(){
this.setName = function(name){
this.name = name;
};
}
Person.prototype.getName = function(){
return this.name;
}
var Author = function(name, books){
this.books = books;
}
Author.prototype.getBooks = function(){
return this.books;
}
var author = new Author('Auth1', ['b1','b2']);
Do explain the authenticity of above 2 code blocks?
I even don't know whether examples quoted above are right or not. If they are not correct than please throw some light on partial inheritance in JavaScript.
Question: I just want to inherit only setName method from Person constructor to Author constructor. Is that possible?
this(unbound). If youbindsomething,thisis replaced with the actual instance object, and is no longer a generic class method that could be called in any context. The difference betweencallandapplyis thatapplyworks withargumentsandarrays(notice they all start with 'a')setNamecreated inside thePersonconstructor and not put as a normal method onPerson.prototype? It doesn't even use anything from the constructor scope.