You have the prototype attached after the object has already been initialized. Moving your prototype assignment before you create the triangle object, would give you access to get_type.
However, because the way you are assigning the prototype, you dont get the reference of actual constructor function name.Primary reason for this behaviour is that you are actually creating an instance of Shape object independent of the constructor and referencing that instance as a prototype for Triangle / Square. Shape constructor doesn't get executed when you instantiate Triangle / Square constructors.
To get around this issue, you could use Function.call.
You could use the code snippet as reference.
In the snippet, you could see the Shape constructor is being called on each Triangle / Square object instantiations and now, you could see the constructor reference as Triangle / Square as per the instance.
But this approach has its own drawback, as you could see any methods that are defined on the prototype of Shape aren't available on the Traiangle / Square. To make this work, you need to have your methods in Shape constructor and not use prototype, if you are ok with it.
function Shape() {
this.type = 'emptyString';
this.get_type = function() {
console.log(this.constructor.name)
}
}
Shape.prototype.getSomeValue = function() {
console.log("1234");
}
function Triangle(s1, s2, s3) {
Shape.call(this);
this.side1 = s1;
this.side2 = s2;
this.side3 = s3;
}
function Square(s1, s2, s3, s4) {
Shape.call(this);
this.side1 = s1;
this.side2 = s2;
this.side3 = s3;
this.side4 = s4;
}
var triangle = new Triangle(10, 8, 15);
console.log(Triangle.prototype); //Shows the Shape() function on console.
console.log(triangle.side1, triangle.side2, triangle.side3) //Shows the Triangle constructor works.
console.log(triangle.type); //Undefined
triangle.get_type();
var square = new Square(2, 2, 2, 2);
console.log(square.side1, square.side2, square.side3, square.side4);
console.log(square.type);
square.get_type();
try {
triangle.getSomeValue();
} catch (e) {
console.log(e.message);
}
try {
square.getSomeValue();
} catch (e) {
console.log(e.message);
}