[英]Javascript Object Prototype TypeError: … is undefined
I'm have a problem with calling the method in the prototype, which returns: 我在调用原型中的方法时遇到问题,该方法返回:
TypeError: this.backgroundImagesReplace(...) is undefined
TypeError:this.backgroundImagesReplace(...)未定义
this.backgroundImagesReplace(data)
this.backgroundImagesReplace(数据)
My code looks like the following: 我的代码如下所示:
var Template = function() {};
Template.prototype = {
backgroundImagesReplace : function(data) {
var defer = $.Deferred();
// some code that resolves the deferred object
defer.resolve(data);
},
replace : function(data, callback) {
this.backgroundImagesReplace(data)
.done(this.replaceContent)
.done(this.replaceElement)
.done(this.replaceAttribute)
.done(systemObject.executeCallBack(callback));
},
init : function() {
this.replace([], function() {
console.log('here');
});
}
};
var TemplateObject = new Template();
TemplateObject.init();
Any idea what might be causing it? 知道是什么原因造成的吗?
You've forgotten to return the object in your backgroundImagesReplace
function. 您忘记了在
backgroundImagesReplace
函数中返回该对象。 While you could return the Deferred
object directly, it would be advisable to return a Promise
object instead, as that's more suitable for passing to other objects/functions. 虽然您可以直接返回
Deferred
对象,但建议改为返回Promise
对象,因为它更适合传递给其他对象/函数。 Deferred
objects should be kept private as their state can be directly changed, while it is much more difficult to accidentally change the state through a Promise
object. Deferred
对象应保持私有状态,因为它们的状态可以直接更改,而通过Promise
对象意外更改状态要困难得多。 You can do that by doing the following: 您可以通过执行以下操作来做到这一点:
backgroundImagesReplace : function(data) {
var defer = $.Deferred();
// some code that resolves the deferred object
defer.resolve(data);
return defer.promise();
},
This gives you that TypeError
as your code is attempting to access a property of undefined
, which (of course) will not do what you expected it to do. 这会在您的代码尝试访问
undefined
属性时为您提供TypeError
,这(当然)不会执行您期望的操作。
Your method backgroundImagesReplace does not return anything. 您的方法backgroundImagesReplace不返回任何内容。 So the result of calling it is undefined, on which you are trying to call
.done()
. 因此,调用它的结果是不确定的,您尝试在其上调用
.done()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.