在未实现接口XMLHttpRequest的对象上调用错误“打开"
当我尝试从另一个类函数的一个类内部启动ajax请求时,出现此错误.您可以从以下示例中在firefox控制台中获取错误:
I get this error when I'm trying to launch an ajax request inside of a class from another class function. You can get the error in firefox console from this example:
https://jsfiddle.net/d2o1d0eu/
http://codepen.io/anon/pen/dGwwKG
var MyClass = new Class({
initialize: function(options){
this.my_request = new Request({
url: '/echo/html/',
method: 'post',
onSuccess: function(resp) {
alert(resp);
}
});
},
request: function(param){
this.my_request.send('html='+param);
}
});
var MySecondClass = new Class({
Implements: [Options],
options: {
first_class: {}
},
initialize: function(options){
this.setOptions(options);
this.options.first_class.request('internal'); // error
},
request: function(param){
this.options.first_class.request(param);
}
});
var unknown_name = new MyClass();
// unknown_name.request('unknown_name test'); // ok
var test = new MySecondClass({
'first_class': unknown_name
});
// test.request('second class test'); // error
感谢任何建议,谢谢.
Internally, the Options
mixin uses Object.merge
, which does a recursive copy of the passed options
argument.
在您的代码中,您要将 MyClass
的实例作为选项传递给 MySecondClass
的实例.当您以这种方式传递对象时, Object.merge
将递归克隆对象.这意味着在您的第二个类中, this.options.first_class.my_request
实际上是 Request
实例的 clone ,其中包含所有实例对象属性也将被克隆.
In your code, you're passing an instance of MyClass
as an option to an instance of MySecondClass
. When you pass an object this way, Object.merge
will recursively clone the object. That means that in your second class, this.options.first_class.my_request
is actually a clone of a Request
instance, with all of the instance's object properties being cloned as well.
这带来了一个问题,因为在该过程中克隆了 Request
类的实际 XMLHttpRequest
对象.最后得到的是一个基础对象(即,它仅从 Object.prototype
继承),具有一个实际的 XMLHttpRequest
实例的所有属性和方法,但是是不是实际实例.由于 XMLHttpRequest
的方法认为您正在尝试在非实例上调用这些方法,因此会出现DOMException.
This presents a problem, since the actual XMLHttpRequest
object of the Request
class is cloned in the process. What you get in the end is a base object (i.e, it only inherits from Object.prototype
) that has all the properties and methods of an actual XMLHttpRequest
instance but is not an actual instance. Since the methods of XMLHttpRequest
think that you're trying to call the methods on non-instances, you get a DOMException.
要点是:不要将 Class
实例作为选项传递.而是将它们作为单独的参数传递: new MySecondClass(unknown_name,options)
.
The take-away is this: do not pass Class
instances as options. Instead, pass them as separate parameters: new MySecondClass(unknown_name, options)
.