Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
Is this a function construct feature or Vue 3 or Javascript generally, and how do I pass "this" variables to it?

I am new to Vue 3 and whilst I use Javascript regularly I am not an expert at it. In my Vue 3 project, I found (not on SO) a solution to a particular challenge to deploy Stripe's paymentRequest method. I got the example code to work, but it only works properly when wrapped within this (to me) strange void function construct. However, when wrapped in this construct, I can no longer access variables otherwise available through the 'this' object, so outside the function I can access 'this.myVar' inside I can't.

I found a solution to this but it feels clunky and I am sure there is a better way. The clunky way is to assign any 'this' variables to global javascript variables (within the script tag) just before this construct runs - it works, but doesn't feel the best way by a long stretch. Here is the code in example form...

<script> //section of Vue

var myVar = "";

export default {
  name: 'myVueScreen',
  data() {
    return {
      myVar: "foo",
    },
  }
  methods: {
   myMethod() {

    console.log(this.myVar); //prints 'foo'

    myVar = this.myVar;

    console.log(myVar); //prints 'foo'


    // strange function construct... what is this??
    (function () { 

       console.log(myVar); //prints 'foo'
       console.log(this.myVar); fails with this.myVar undefined

    })(); // I really don't understand the role of the 'extra' ()


   }
  }
}

Can anyone tell me what's actually going on with this (function () {.. construct, why 'this.myVar' is outside scope somehow and therefore failing as undefined, and whether there is a way to pass 'this.myVar' to it without using global JS variables as I currently am... thanks!

BTW, I did find that you can pass variable values into this function as follows, BUT this approach still cannot see 'this.myVar'

So this works...

    (function (bar = "foo") { 

       console.log(bar); //prints 'foo'

...

..and this doesn't, it fails at the first point it tries to read this.myVar:

    (function (bar = this.myVar) { //fails here when reading 'this.myVar'

       console.log(bar); // never reaches this
...
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!