Unsolved this context
-
Why this context wrong in onreadystatechange?
import QtQuick 2.0 Item { id: root Component.onCompleted: { console.log("Component completed") console.log(this.__proto__.constructor.name); // Object String.prototype.repeat = function(times) { return Array(++times).join(this); }; // works console.log("*".repeat(10)); function Foo(x) { this._x = x; } Foo.prototype.getX = function() { return this._x; } // works var foo = new Foo(42); new Foo("bar"); console.log(foo.getX()); // 42 console.log(this.root); // undefined var xhr = new XMLHttpRequest; xhr.open("GET", "http://httpbin.org/get"); xhr.onreadystatechange = function() { // wrong this context if (this.readyState == this.DONE && this.status == 200) { console.log(this === xhr); // false console.log(this.response); // undefined } // it's works if (xhr.readyState == xhr.DONE && xhr.status == 200) { console.log(xhr.response); } }; xhr.send(); } }
-
Because you are using the this keyword inside the Item element, therefore in your example code, this refers to the Item. That's why console.log(this === xhr); is false. Therefore your last conditional should be like this:
if (xhr.readyState == xhr.DONE && xhr.status == 200) { console.log(xhr.response); }
-
Ok.
import QtQuick 2.0 import "assets/scripts/test.js" as Q Item { id: root Text { text: "Test!" } }
assets/scripts/test.js
(function() { var xhr = new XMLHttpRequest; xhr.open("GET", "http://httpbin.org/get?foo=bar"); xhr.onreadystatechange = function() { console.log(this == xhr); }; xhr.send(); })();
Console output:
Запускается C:\Qt\5.5\mingw492_32\bin\qmlscene.exe... qml: false qml: false qml: false C:\Qt\5.5\mingw492_32\bin\qmlscene.exe завершился с кодом 0