[QML]javascript global "this"
-
In my QML project,
@
//test.js
function func() { //func is the entrance function.
foo.apply({a:100},[])
}function foo(){
console.log("foo.this->"+this.a);//output:100
Qt.include("test2.js");
}@@
//test2.js
console.log(this.a);//output:undefined
@what's more,it will cause error if write like this:
@
//test.js
this.xxx =100; //=>TypeError: Cannot assign to read-only property "xxx"
@qestion:
(1)what is the global "this" object in javascript file?
(2)why test2.js does not share the "this" object with its caller "foo"? -
Hi,
In QML, "this" is only defined when used in property bindings of QML components. There is no global "this".
See:
- "Using this with Property Binding":http://qt-project.org/doc/qt-5/qtqml-syntax-propertybinding.html#using-keyword-this-keyword-with-property-binding
- "JavaScript Environment Restrictions":http://qt-project.org/doc/qt-5/qtqml-javascript-hostenvironment.html#javascript-environment-restrictions
-
Unfortunately, your .js file cannot use this.
You have two options:
Put the code inside your QML window component itself, OR
Give your JS function a var argument, and pass your window into the JS function.
This page might help: http://stackoverflow.com/questions/19782933/how-to-pass-this-from-a-qml-element-to-a-js-function