Class Inheritance using Object.extendsObject and this.name

OliverDoesereck
Tera Guru

I am trying something thats pretty simple and should work fine, as there are more than enough example Script Includes, but something just doesnt work.

Animal Class:

var Animal = Class.create();
Animal.prototype = {
    initialize: function(name) {
        this.name = name;
        this.speed = 0;
    },

    run: function(speed) {
        this.speed += speed;
        gs.log(this.name+" runs with speed "+this.speed+".");
    },

    stop: function() {
        this.speed = 0;
        gs.log(this.name+" stands still.");
    },

    type: 'Animal'
};

Rabbit Class, extending Animal Class:

var Rabbit = Class.create();
Rabbit.prototype = Object.extendsObject(Animal, {

	hide: function() {
		gs.log(this.name + " hides!");
	},
	
	type: "Rabbit"
});

As already learned, Object.extendsObject is a ServiceNow extension of prototype.js  (Script Include: PrototypeServer)

When executing the following:

var rabbit = new Rabbit("White Rabbit");
rabbit.run(5);

The Output is:

*** Script:  runs with speed 5.

Findings:
- this.name is not being set in the constructor. If I exchange "name" with "myName", everything works fine when using this.myName.
- using Object.extend(new Animal(), {}) works fine too. But thats the legacy way.
- using the Class Extender Method from Raymond Ferguson here: https://community.servicenow.com/community?id=community_question&sys_id=fb3f4be1dbdcdbc01dcaf3231f9619b1 works fine too.
- Creating a new Animal Object works fine with "name"

Is "name" protected or reserved when extending classes using Object.extendsClass? The parent constructor is being called just fine. this.speed is being used correctly.

3 REPLIES 3

Sebastian R_
Kilo Sage

An instance of a script include always contains a variable "name" (don´t know why). It´s empty and I assume this is somehow protected if you clone/exten a script include.

typeof new Animal().name; // -> string

I think it´s the best to use another name for it.

Geni
Tera Contributor

when calling Object.objectExtends you need to manually call the initialization method of the class your extending in your case modify your rabbit script include to the following:

var Rabbit = Class.create();
Rabbit.prototype = Object.extendsObject(Animal, {

       initialize: function() {
		Animal.prototype.initialize.call(this);
      },

	hide: function() {
		gs.log(this.name + " hides!");
	},
	
	type: "Rabbit"
});

 

By calling the Animal prototype initialize and feeding the instance of this you will apply your initialize logic to your extended class.

BillMartin
Mega Sage

Hi @OliverDoesereck ,

 

I have created this easy to follow example where you can inherit from a class using Object.extendsObject() function. 

 

You can find more details here: Master Good Software Architecture with Object.extendsObject() | A Guide for ServiceNow Developers