简体   繁体   中英

Bind imported function context

Considering the following example is there a valid way to bind the function to whatever context it is being executed in?

// External.js
function onInput () {
  console.log(data)
}


// Index.js
import { onInput } from 'external.js'

const data = 1
const input = document.querySelector(`input`)
input.addEventListener(`input`, onInput)

JavaScript has lexical scope, not dynamic scope. This is not possible.

You could define data in a scope that onInput can access and provide a way to change the value of data , eg

// External.js
let data;

export function setData(v) {
  data = v;
}

export function onInput () {
  console.log(data)
}

// Index.js
import { onInput, setData } from 'external.js'

setData(1);
const input = document.querySelector(`input`)
input.addEventListener(`input`, onInput)

Other options:

Make the value an argument of the function. That's probably the more traditional way:

// External.js
export function onInput (data) {
  console.log(data)
}

// Index.js
import { onInput } from 'external.js'

const data = 1;
const input = document.querySelector(`input`)
input.addEventListener(`input`, () => onInput(data))

Make data a property of the function itself:

// External.js
export function onInput (data) {
  console.log(onInput.data)
}

// Index.js
import { onInput } from 'external.js'

onInput.data = 1;
const input = document.querySelector(`input`)
input.addEventListener(`input`, onInput)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM