3
Hello!
I’m studying javascript, but specifically Parasitic Combination Inheritance, and came across the methods override. It turns out I created the following code:
var Base = function(nome, texto) {
this.name = nome;
this.text = texto;
this.saudacao = function() {
return this.text + ' ' + this.name;
}
}
var heranca = function(p, f) {
var pc = Object.create(p.prototype);
f.prototype = pc;
f.prototype.constructor = f;
}
var Dia = function(texto) {
Base.call(this, 'Fulano? ', 'Tudo bem, ');
this.newText = texto;
}
heranca(Base, Dia);
Dia.prototype.saudacao = function() {
var msg = this.saudacao();
return msg + ' ' + this.newText;
}
var ola = new Dia('Bom dia!');
alert(ola.saudacao());
When executing Alert(hello(greeting)), I have the return of the parent class, not the superscript.
For testing, I changed the name of the method "greeting" of the class "day" to "novaSaudacao" and, executing Alert(hello.novaSaudacao()), I get the correct output.
Apparently the code written in dia.prototype.saudacao = Function() {} is not even executed (I added an Alert('! ') in him and it had no effect).
Hence the question: how to work correctly with the superscript of methods in javascript without forgetting the Parasitic Combination Inheritance?
EDIT I will try to explain the practical application to clarify the issue a little. The objects used as an example are not in question, only their functionalities.
Consider a class that calls itself "Kindness" and has the method "Greeting".
In creating...
var ola = new Gentileza("José");
We can execute...
ola. Greeting();
And as a result, "Hello, Jose.".
Now, we need two other objects called "Day" and "Night" which are children of "Kindness". So we can create...
var dia = new Dia("José");
And execute...
day. Greeting();
Now, the message will be "Hello Joseph. Good morning!". The first part of the message ("Hello, Joseph.") was generated in the parent object (Kindness). The "Day" object inherited the greeting from the parent object and added "Good morning!" to the text.
For the purpose of completion: I intend that my child class inherits a parent class method and complements it.
Thank you for your attention.
What you want with the line
var msg = this.saudacao();
? I couldn’t tell from your code...– BrnPer
What final return you want?
– FabianoLothor
Brnper The variable "msg" contains the recovered text of the parent class. I use it just below by adding a text to complement the greeting and include a "good morning". It could also be Return this.saudacao() + ' ' + this.newText.
– Leikovsk
Fabianolothor, the return should be: "All right, so-and-so? Good morning!"
– Leikovsk
His parent class creates a method that "overwrites" (Shadows) what is in the prototype. It seems that you are understanding the opposite, but it is not very clear the question.
– bfavaretto