我正在Servoy中开发使用 Servoy JavaScript 框架的快速应用程序开发工具,难以通过向其原型(prototype)添加方法来扩展对象。
在普通 JavaScript 中,您可以扩展对象的原型(prototype)来添加方法。当您想要拥有一个类的多个实例并且不希望每个对象在内存中重新定义相同的方法时,可以使用此技术来节省内存。
当我尝试在 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 环境中使用原型(prototype)扩展对象而不引发此错误?
最佳答案
为了防止 Servoy 抛出错误,您必须将其包装在立即调用的函数中并将其存储在变量中。当 Servoy 读取 JavaScript 文件时,它会看到立即调用的函数,执行它,然后将原型(prototype)修改存储到内存中:
这是代码:
// 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;
}
};
}();
当您以这种方式包装原型(prototype)扩展时,Servoy 将不再抛出错误。
关于javascript - 如何在 Servoy 框架中扩展 JavaScript 原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35204487/