Javascript inheritance unable to use base class method - javascript

I'm trying to use inheritance in javascript
here is example C# code to show what I'm attempting
public class animal
{
public animal() { }
public string move()
{
return "i'm moving";
}
public string bite()
{
return "just a nip!";
}
}
public class snake : animal
{
public snake() { }
public string bite()
{
return "been poisoned!";
}
}
used as:
var a = new animal();
var s = new snake();
a.bite(); // just a nip
s.bite(); // been poisoned
a.move(); // i'm moving
s.move(); // i'm moving
now in JS I Have:
function animal() {
};
animal.prototype.move = function () {
return "im moving";
};
animal.prototype.bite = function () {
return "just a nip";
};
snake.prototype = new animal();
snake.prototype = snake;
function snake() {
}
snake.prototype.bite = function () {
return "been poisoned";
};
var a = new animal();
var s = new snake();
alert(a.bite()); // just a nip
alert(s.bite()); // been poisoned
alert(a.move()); //i'm moving
alert(s.move()); // s.move is not a function
Do I have to provide a method in each of the subclasses and call the base method? ie add a move method to snake to call animal.move?
snake.prototype.move = function () {
return animal.prototype.move.call(this);
}

right now you set the prototype twice.
snake.prototype = new animal();
snake.prototype = snake;
the second line should be
snake.prototype.constructor = snake;

Related

How to create a JS object within constructor and "parent object" as constructors argument?

The question might sound a bit confusing so I'll let the code explain:
function Foo(arg) {
const argument = arg;
const fooPart = new FooPart(this);
this.printArg = function() {
console.log(argument);
}
}
function FooPart(foo) {
this.parent = foo;
this.parent.printArg();
}
let foo = new Foo("this is the argument");
This is not working for me. How can I solve this problem or better - what would be the correct approach for this?
Thanks
function Foo(arg) {
this.argument = arg;
this.fooPart = new FooPart(this);
}
Foo.prototype.printArg = function() {
console.log(this.argument);
}
function FooPart(foo) {
this.parent = foo;
this.parent.printArg();
}
let foo = new Foo("this is the argument");
You should call FooPart after printArg definition
You should use this.parent to access parent
The problem is that you define printArg after trying to call it.
The traditional way to define a "class" which doesn't have this problem would be:
function Foo(arg) {
this.argument = arg;
this.fooPart = new FooPart(this);
}
Foo.prototype.printArg = function() {
console.log(this.argument);
}
function FooPart(foo) {
this.parent = foo;
this.parent.printArg();
}
let foo = new Foo("this is the argument");
The more modern version to define an "actual" class is:
class Foo {
constructor(arg) {
this.argument = arg;
this.fooPart = new FooPart(this);
}
printArg() {
console.log(this.argument);
}
}
class FooPart {
constructor(foo) {
this.parent = foo;
this.parent.printArg();
}
}
let foo = new Foo("this is the argument");

How do I call a child method using the parent object in JavaScript?

I want to call child method using parent object in javascript how can I do it?
var Shape = function () { }
Shape.prototype.draw = function () {
return "Generic shape called ";
}
var Circle = function () { }
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.draw = function () {
return "I am from Circle";
}
var Rectangle = function () { }
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.draw = function () {
return "I am from Rectangle";
}
var Triangle = function () { }
Triangle.prototype = Object.create(Shape.prototype);
I want to access any overridden method like Rectangle, Circle any one but using Shape object like in c# what we can do: Shape shape=new Circle() shape.draw(); it will call overridden method of the child class.I want to do the same thing in javascript how can I achieve it
var Shape = function () { }
Shape.prototype.draw = function () {
return "Generic shape called ";
}
Shape.prototype.val = 10;
var Circle = function () { }
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.draw = function () {
return "I am from Cirlce";
}
var Rectangle = function () { }
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.draw = function () {
return "I am from Rectangle";
}
var Triangle = function () { }
Triangle.prototype = Object.create(Shape.prototype);
Triangle.prototype.draw = function () {
return "I am from Triangle";
}
//Using Up casting (access value of parent object)
var newCircle = new Circle();
alert("newCircle: "+newCircle.draw()+" : "+newCircle.val);
If you are using any subclass of Shape in your code ( you can check at runtime with instanceof operator) you can simple invoke the method. Js runtime would automatically call the right method from the prototype chain. So, if you have an object in code called myshape, you can:
if(myshape instanceof Shape){
// invoke draw method
myshape.draw();
}

How to make a private static array in a javascript class?

I want to make a static array in a javascript class, for this I do:
var Manager = (function () {
function Manager() {
var ubications = new ArrayList();
this.ubicationsArray = function () {
return(ubication);
};
}
Manager.prototype.addUbication = function (ubication) {
Manager.ubicationsArray().add(ubication);
};
Manager.prototype.getUbication = function (index) {
return Manager.ubicationsArray().get(index);
};
Manager.prototype.sizeOfUbications = function () {
return Manager.ubicationsArray().size();
};
return Manager;
}());
Manager["__class"] = "Manager";
Where ubications is the static array and the function ubicationsArray is the public function to acces the array.
I try to use this code with:
var ubication = new Ubication(123,456);
var manager = new Manager();
manager.addUbication(ubication);
alert(manager.sizeOfUbications());
But I got this error:
Uncaught TypeError: Manager.ubicationsArray is not a function
How is the correct way to use static arrays in a javascript code?
Currently, JavaScript can only do privacy with respect to function scope.
function Manager () {
}
Manager.prototype = (function (){
var ubications = [];
return {
addUbication: function (u) {
ubications.push(u);
},
getUbication: function (index) {
return ubications[index];
},
sizeOfUbications: function () {
return ubications.length;
}
};
})();
Inside your constructor function, this.ubicationsArray assigns a property to the instance of the object, not the constructor itself.
Perhaps you want something like this:
function Manager() {
}
var ubications = new ArrayList();
Manager.ubicationsArray = function () {
return(ubication);
};
Note that this property isn't really "private". This would be more-private:
var Manager = (function () {
function Manager() {
}
var ubications = new ArrayList();
Manager.prototype.addUbication = function (ubication) {
ubications.add(ubication);
};
Manager.prototype.getUbication = function (index) {
return ubications.get(index);
};
Manager.prototype.sizeOfUbications = function () {
return ubications.size();
};
return Manager;
}());
Manager["__class"] = "Manager";

Manage JS inheritance failure

I am new to Object Orientated Programming, please have in mind. I have understood how the first part shown here works (it does):
function Car() {
var __registration;
var setReg = function(val) {
__registration= val;
}
var getReg= function() {
return __registration;
}
return {
setReg: setReg ,
getReg: getReg
}
}
var myCar = new Car();
myCar.setReg("LSKM5215");
alert(myCar.getReg() ); //ALERTS LSKM5215
But when trying to manage inheritance on this way of Object Orientated Programming, it just fails once and again:
function Extras(){
var __sound;
var setSound= function(val) {
__sound= val;
}
var getSound= function() {
return __sound;
}
return {
setSound: setSound,
getSound: getSound
}
}
Extras.prototype = new Car();
myCar.setSound("SUPERB SOUNDSYSTEM 2.2"); //TypeError: myCar.setSound is not a function
How could I create inheritance on this case? To make Car() get the private variables about the "soundsystem extras"?
Very grateful.
You not need return when plan use function as constructor.
in derived class you should call base constructor with needed parameters.
in derived class assign proptotype based on base prototype.
Something like this:
function Car() {
var __registration;
this.setReg = function(val) {
__registration = val;
}
this.getReg = function() {
return __registration;
}
}
function Extras() {
Car.call(this);
var __sound;
this.setSound = function(val) {
__sound = val;
}
this.getSound = function() {
return __sound;
}
}
Extras.prototype = Object.create(Car.prototype);
myExtras = new Extras();
myExtras.setReg("LSKM5215");
myExtras.setSound("SUPERB SOUNDSYSTEM 2.2");
document.write("<div>Extras: reg - ", myExtras.getReg(), '</div>');
document.write("<div>Extras: sound - ", myExtras.getSound(), '</div>');
And for ES2015 you can use classes
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
}
class Car {
constructor() {
this.__registration = undefined;
}
set Reg(val) {
this.__registration = val;
}
get Reg() {
return this.__registration;
}
}
class Extras extends Car {
constructor() {
super();
this.__sound = undefined;
}
set Sound(val) {
this.__sound = val;
}
get Sound() {
return this.__sound;
}
}
myExtras = new Extras();
myExtras.Reg = ("LSKM5215");
myExtras.Sound = ("SUPERB SOUNDSYSTEM 2.2");
document.write("<div>Extras: reg - ", myExtras.Reg, '</div>');
document.write("<div>Extras: sound - ", myExtras.Sound, '</div>');

Multi Level Inheritance in Javascript

I am trying to mock inheritance in Javascript using prototype.
I have a function named Model and a type of model => Item.
var Model = function() {
this.names = ["name1", "name2"];
}
Model.prototype.Item = function(args) {
this.init = function(item_name) {
this.names[0] = item_name; // ERROR: Cannot set property '0' of undefined
}
}
var m = new Model();
var i = new m.Item();
i.init("New Name"); // ERROR: Cannot set property '0' of undefined
How can I access names array from init() function above?
Inheritance in Javascript is tricky! Read this post for a great explanation of traditional object oriented inheritance in Javascript: http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/.
var Model = function () {
this.names = ["name1", "name2"];
};
var Item = function () {
//When inheriting in Javascript you must
//call the inherited function's constructor manually.
Model.call(this);
};
//Inherit Model's prototype so you get all of Model's methods.
Item.prototype = Object.create(Model.prototype);
Item.prototype.constructor = Item;
Item.prototype.init = function (item_name) {
this.names[0] = item_name;
};
var Employee = function () {
Model.call(this);
};
Employee.prototype = Object.create(Model.prototype);
Employee.prototype.constructor = Employee;
var myItem = new Item();
myItem.init("New Name");
//prints New Name, name2
console.log(myItem.names);
var myEmployee = new Employee();
//prints name1, name2
console.log(myEmployee.names);
Analogous code in a more traditional object oriented language (C#):
public class Model
{
public Model()
{
this.Names = new[] {"name1", "name2"};
}
public string[] Names { get; set; }
}
public class Item : Model
{
public Item() : base() { }
public void init(string item_name)
{
this.Names[0] = item_name;
}
}
public class Employee : Model
{
public Employee() : base() { }
}
var myItem = new Item();
myItem.init("New Name");
//prints New Name, name2
Console.WriteLine(String.Join(",", myItem.Names));
var myEmployee = new Employee();
//prints name1, name2
Console.WriteLine(String.Join(",", myEmployee.Names));
The issue you're having is that in the second item Item, your reference to this has no idea about it's "parent" object Model.
One way to re-write this is like so:
var Model = function() {
this.names = ["name1", "name2"];
}
Model.prototype.init = function(item_name) {
this.names[0] = item_name;
}
var Item = new Model();
Item.init("New Name");
console.log(i);
Fiddle here: http://jsfiddle.net/BksS3/1/
As far as making this work is concerned, this would work too.
var Model = function() {
this.names = ["name1", "name2"];
}
Model.prototype.Item = function(args) {
this.init = function(item_name) {
this.names[0] = item_name;
}
}
var m = new Model();
var i = new m.Item();
i.init.apply(m,["New Name"]);
Manager class object will access all method from Person and Employee.
Multilevel Inheritance example
function Person(firstName,lastName,marks,age,gender)
{
this.firstName = firstName;
this.lastName = lastName;
this.age=age;
this.gender=gender;
}
Person.prototype.getFullname = function()
{
console.log("Full Name is "+this.firstName +' '+this.lastName);
}
function Employee(firstName,lastName, marks, rollno, salary)
{
Person.call(this,firstName,lastName,marks, rollno, salary);
this.rollno = rollno;
this.salary=salary;
}
function Manager(firstName,lastName, marks, rollno, salary, code) {
Employee.call(this, firstName,lastName,marks, rollno, salary, code);
this.code = code;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.getSalary = function()
{
console.log(`Salary of ${this.firstName} ${this.lastName} is ${this.salary}`);
}
Manager.prototype = Object.create(Employee.prototype);
Manager.prototype.constructor = Manager;
Manager.prototype.designation = function() {
console.log("You'r designation is Manager");
}
var m = new Manager("shankar","singh", 21,100, 40000,"CS12");
console.log(m);
m.getFullname();
m.getSalary();
m.designation();
</script>
This is how you implement multi-level inheritance in JavaScript.
<script>
//Multi Level Inheritance Example
//Parent Class
class A{
constructor()
{
this.a=0;
}
setA()
{
this.a=10;
}
}
//Child Class
class B extends A{
constructor()
{
super();//call parent class constructor
this.b=0;
}
setB()
{
this.b=20;
}
}
class Addition extends B{
add()
{
this.setA();
this.setB();
return this.a+this.b;
}
}
class Print extends Addition{
print()
{
var result=this.add();
document.write("<br/>a="+this.a);
document.write("<br/>b="+this.b);
document.write("<br/>Addition="+result);
}
}
//Make Object
let obj=new Print();
obj.print();
/*
Assignment:
Make subtraction, multiplication, diuvision classes and print the output as
==============
Two Digit Calculator
==============
a=10
b=20;
Addition=30
Subtraction=-10
Multiplication=200
Division:.5
*/
</script>

Categories