How to extend a JavaScript prototype in the Servoy Framework?

323 Views Asked by At

I am developing in the Servoy Rapid Application Development Tool using the Servoy JavaScript Framework and having difficulty extending an object via adding methods to it's prototype.

In normal JavaScript you can extend the object's prototype to add methods. This technique is used to save memory when you want to have multiple instances of a class and do not want each object to redefine the same method in memory.

When I try to do this in the Servoy JavaScript framework, Servoy throws an error, here is my code:

// Create the object
function Person(firstname, lastname) { 
    this.firstname = firstname; 
    this.lastname = lastname;
}
Person.prototype.greet = function () {
    application.output('Hello, my name is '+this.firstname);
    return;
}
Person.prototype.stateFullName = function () {
    application.output('My full name is: '+this.firstname+' '+this.lastname);
    return;
}

This code throws the following error in Servoy:

The property greet is undefined for the javascript type Object

How can I extend an object using prototype in the Servoy environment without this error being thrown?

1

There are 1 best solutions below

0
On BEST ANSWER

To prevent Servoy from throwing the error you must wrap it in an immediately invoked function and store it in a variable. When Servoy reads the JavaScript file it will see the immediately invoked function, execute it and in turn store the prototype modifications into memory:

Here is the code:

// Create the object
function Person(firstname, lastname) { 
    this.firstname = firstname; 
    this.lastname = lastname;
}

// Extend prototype to add methods:
var seeMyPersonPrototypeExtensionsServoy = function(){

    Person.prototype = {

        greet: function () { 
            application.output('Hello, my name is '+this.firstname);
            return;
        },

        stateFullName: function() {
            application.output('My full name is: '+this.firstname+' '+this.lastname);
            return;
        }
    };

}();

Servoy will no longer throw the error when you wrap the prototype extensions in this manner.