
Servoy Tutorial Photo Credit: Thomas Hawk via Compfight
This is an object-oriented Servoy tutorial on how to use multiple inheritance with Servoy. If you read the article on “Prototypal Inheritance”, then you learned all about cloning objects using a standard function called objectPlus. This function cloned an object with all its properties and functions, and returned a new object to us, which we could then modify and use to clone new objects from. We applied this approach to a car dealership, creating a vehicle constructor function with basic properties, modifying it with a car constructor function, and then finally making a sports car object for our sexy corvette.
In this article, we will introduce a new standard method called objectMulti, that takes any number of objects, and makes a new object that contains all the properties and functions from all the original objects. In other words, you could have three separate literal objects, and combine them all into one new object, with this single function. Very slick indeed!
In real programming scenarios, different objects may would contain properties and functions that represent different features and capabilities. We can pick and choose from our library, combining the objects to make one super object that inherits all the properties and functions from the individual objects. It’s kind of like a recipe to make something new from individual ingredients, where the ingredients are the individual objects.
Okay, here is the objectMulti function. Copy and paste this code into your utility library. You will find a use for it, trust me.
1 2 3 4 5 6 7 8 9 10 11 12 | function objectMulti(arg) { var n = {}, stuff, j = 0, len = arguments.length; for (j = 0; j < len; j++){ stuff = arguments[j]; for (var i in stuff){ if (stuff.hasOwnProperty(i)){ n[i] = stuff[i]; } } } return n; } |
1 2 3 4 5 6 7 8 9 | function Vehicle(){ var vehicle = { name: 'unknown', make: 'unknown', color: 'unknown', mgp: 0 }; return vehicle; } |
1 2 3 4 5 6 | function Car(){ var car = { type: 'unknown' }; return car; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function SportsCar(){ var sportsCar = { type: "Sports Car", premiumPaint: 'unknown', getInfo: function(){ return this.color + " " + this.make + " " + this.name + " " + this.type + " - " + this.mpg + "mpg" + " - " + this.premiumPaint; } }; return sportsCar; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | var vehicle = new Vehicle(); var car = new Car(); var sportsCar = new SportsCar(); var myCorvette = objectMulti( vehicle, car, sportsCar, { name: "Corvette", make: "Chevy", color: "White", premiumPaint: 'Pearl White', mpg: 10 }); application.output(myCorvette.getInfo()); //White Chevy Corvette Sports Car - 10mpg - Pearl White |