javascript - How to call a method in class from its replaced implementation? -
,
I'm trying to understand some concepts in JavaScript. Consider the following code:
function person (name, age) {this.name = name || "no name"; This.age = age || "Age is not specified"; This.printStr = function () {console.log ("& lt;" + this.name + "," + this.age + "& gt;"); }; } P = new person ("Pranav", 26); P.printStr = function () {console.log ("This works .... even .... ...." + this.name); }; P.printStr ();
I want to call the 'printStr' implementation in the person class from within the 'printStr' function implementation in 'P'.
It should do that the output is required:
Any thoughts? :)
The way your code is now set up, you can not do this. When you call person
as a constructor, the object that is going to be p
is set to this
. So when you define printStr
in the constructor, then p
gets a property named printStr
. When you assign another function, you write it over over.
Two options: There is no answer which is pblochane - the internal code is called oldPrintStr
. Another option is to use prototype legacy:
function person (name, age) {this.name = name || "no name"; This.age = age || "Age is not specified"; } Person.prototype.printStr = function () {console.log ("& lt;" + this.name + "," + this.age + "& gt;"); };
Then you can do this:
p = new person ("Pranav", 26); P.printStr = function () {person.prototype.printStr.apply (this); Console.log ("It works .... even ...." + this.name); }; P.printStr ();
Comments
Post a Comment