在下面的代码中,我想通过构造函数提供通用函数。该对象用于处理对 API 的调用。但如果我从 events.POST 调用 this._isEmpty(obj) 它总是返回 false。放置 _isEmpty() 函数的主体确实给出了所需的结果。我该如何解决这个问题? 当然,欢迎任何有关改进此结构的建议。 我在 SO 上查找了一些类似的问题,但我发现的问题/答案没有类似的嵌套。
我调用以下电话:
var assystBridge = new global.assystBridge();
response.setStatus(assystBridge.events.POST(request, response));
对象:
var assystBridge = Class.create();
assystBridge.prototype = {
initialize: function() {
// Generic functions go here
function _isEmpty(obj){
// Checks whether an object has properties
// Used for checking whether any data was posted or not
// Returns true or false
return Object.keys(obj).length === 0;
}
},
events: {
POST: function(request, response){
var data = request.body.data;
var responseText = '';
if(this._isEmpty(data)){
//if(Object.keys(data).length === 0){
response.setBody({"response":"NO data was posted", "data": data});
return 400;
} else {
return 201;
}
},
GET: function(request, response){
},
DELETE: function(request, response){
}
},
type: 'assystBridge'
};
最佳答案
如果将泛型函数移出 initialize()
方法,并将其作为原型(prototype)的属性之一,那么您可以通过 assystBridge.prototype._isEmpty( )
。
例如:
assystBridge.prototype = {
_isEmpty: function(obj) {
// Checks whether an object has properties
// Used for checking whether any data was posted or not
// Returns true or false
return Object.keys(obj).length === 0;
},
events: {
POST: function(request, response){
var data = request.body.data;
var responseText = '';
if(assystBridge.prototype._isEmpty(data)){
response.setBody({"response":"NO data was posted", "data": data});
return 400;
} else {
return 201;
}
},
},
type: 'assystBridge'
};
关于javascript - 嵌套对象内的函数调用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39598247/