I have updated your sketch code to work hopefully you will see why it works. I suggest that you watch this video on instance mode
function textBox(p) {
p.name = 'textBox';
p.s = 50;
p.ex = 10;
p.preload = function () {
// p.icon = p.loadImage('assets/textBox.png');
}
p.setup = function () {
p.createCanvas(1500, 500);
p.background(200);
p.txt = ["Hello World", "welcome to Processing"];
};
p.draw = function () {
p.background(200);
p.textRegion(300, p.height / 2 - p.ex, p.s + p.ex, p.ex, p.txt, p.s);
};
p.textRegion = function (r1, r2, r4, stroke, _text, _size) {
let r3 = p.textWidth(p.join(_text, ' ')) + p.ex;
p.strokeWeight(stroke);
p.fill(255);
p.rect(r1, r2, r3, r4);
p.fill(0);
p.textSize(_size);
p.text(p.join(_text, ' '), r1 + stroke, r2 + _size);
p.noFill();
p.rect(r1, r2, r3, r4);
};
p.keyPressed = function () {
i = txt.length;
p.txt[i] = p.key.toLowerCase();
if (p.txt.length > (p.width - p.ex * 2) / p.s) {
p.txt.splice(0, 1);
}
};
}
let p = new p5(textBox);
BTW it appears most programmers use let in preference to var the difference is in the scoping rules but I find let because you have to declare the variables before you use them.