如何在Servoy框架中扩展JavaScript原型?

时间:2016-02-04 15:04:21

标签: frameworks

我正在使用Servoy JavaScript框架在Servoy快速应用程序开发工具中进行开发,并且难以通过向其原型添加方法来扩展对象。

在普通的JavaScript中,您可以扩展对象的原型以添加方法。当您想拥有一个类的多个实例并且不希望每个对象在内存中重新定义相同的方法时,此技术用于节省内存。

当我尝试在Servoy JavaScript框架中执行此操作时,Servoy会抛出错误,这是我的代码:

// 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;
}

此代码在Servoy中抛出以下错误:

The property greet is undefined for the javascript type Object

如何在Servoy环境中使用原型扩展对象而不抛出此错误?

1 个答案:

答案 0 :(得分:1)

要防止Servoy抛出错误,必须将其包装在一个立即调用的函数中并将其存储在变量中。当Servoy读取JavaScript文件时,它将看到立即调用的函数,执行它,然后将原型修改存储到内存中:

以下是代码:

// 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将不再抛出错误。