如何在 Servoy 框架中扩展 JavaScript 原型?
How to extend a JavaScript prototype in the Servoy Framework?
我正在使用 Servoy JavaScript 框架在 Servoy 快速应用程序开发工具中进行开发,并且难以通过向其原型添加方法来扩展对象。
在正常情况下 JavaScript 您可以扩展对象的原型以添加方法。当你想要一个class的多个实例并且不希望每个对象在内存中重新定义相同的方法时,这个技术被用来节省内存。
当我尝试在 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 环境中使用原型扩展对象而不抛出此错误?
为防止 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 将不再抛出错误。
我正在使用 Servoy JavaScript 框架在 Servoy 快速应用程序开发工具中进行开发,并且难以通过向其原型添加方法来扩展对象。
在正常情况下 JavaScript 您可以扩展对象的原型以添加方法。当你想要一个class的多个实例并且不希望每个对象在内存中重新定义相同的方法时,这个技术被用来节省内存。
当我尝试在 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 环境中使用原型扩展对象而不抛出此错误?
为防止 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 将不再抛出错误。