Inheritance is a very useful design pattern for all programming languages. However, the ServiceNow documentation dies not make it clear how this pattern can be used.
Generally, the advice is to use Composition rather than Inheritance. Inheritance can be a rather brittle design pattern and often exposes too much of the interface of the parent class – so use Inheritance with careful consideration. Some might argue that Javascript has no “private” access modifier – so everything is exposed.
The code below contains an example of how inheritance can be implemented. Take a look at the “call” statement on line 18.
var Parent = Class.create();
Parent.prototype = {
initialize: function(a) {
this.a = a;
this.b = "B";
gs.info("parent initialize, a = " + this.a + ", b = " + this.b );
},
type: 'Parent',
doIt: function() { gs.log("Parent: Do IT"); },
sayHello: function() { gs.log("Hello"); },
};
var Child = Class.create();
Child.prototype = Object.extendsObject(Parent, {
initialize: function() {
Parent.prototype.initialize.call(this, 3);
this.a = 5;
gs.info("child initialize, a = " + this.a + ", b = " + this.b );
},
type: 'Child',
doIt: function() { gs.log("Child: Do IT"); }
});
var c = new Child();
c.doIt();
c.sayHello();
Leave a Reply