Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. QML and Qt Quick
  4. [QML]javascript global "this"
Forum Updated to NodeBB v4.3 + New Features

[QML]javascript global "this"

Scheduled Pinned Locked Moved QML and Qt Quick
3 Posts 2 Posters 1.3k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • W Offline
    W Offline
    wade-J
    wrote on last edited by
    #1

    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"?

    1 Reply Last reply
    0
    • JKSHJ Offline
      JKSHJ Offline
      JKSH
      Moderators
      wrote on last edited by
      #2

      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

      Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

      1 Reply Last reply
      0
      • JKSHJ Offline
        JKSHJ Offline
        JKSH
        Moderators
        wrote on last edited by
        #3

        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

        Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved