Я кодировал функцию для построения графиков на JS. Вот оно:
var x = 0;
var y = 0;
var prevx = 0;
var prevy = 0;
var zoom = 25;
function plot(func) {
this.func = func;
this.x = x;
this.y = y;
this.prevx = prevx;
this.prevy = prevy;
function draw() {
c.beginPath();
c.moveTo(this.prevx * zoom, this.prevy * zoom);
c.lineTo(this.x * zoom, this.y * zoom);
c.strokeStyle = '#fff';
c.stroke();
this.prevx = this.x;
this.prevy = this.y;
this.x += 0.1;
this.y = func(this.x);
}
function animate() {
requestAnimationFrame(animate);
draw();
}
animate();
}
plot(Math.sin);
plot(Math.cos);
// plot(Math.tan);
Почему две функции мешают, даже если я использую ключевое слово это?
На самом сайте уже много похожих вопросов, но я не могу получить ответ, поэтому задал здесь.
Заранее спасибо!



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Когда вы используете ключевое слово this внутри функции, оно относится к самой функции. Здесь вы хотите, чтобы он ссылался на функцию «plot», когда вы находитесь внутри функции «draw». Вы можете сделать это, создав новую переменную в функции "plot" и используя ее. то есть "это".
var x = 0;
var y = 0;
var prevx = 0;
var prevy = 0;
var zoom = 25;
function plot(func) {
var that = this;
this.func = func;
this.x = x;
this.y = y;
this.prevx = prevx;
this.prevy = prevy;
function draw() {
c.beginPath();
c.moveTo(that.prevx * zoom, that.prevy * zoom);
c.lineTo(that.x * zoom, that.y * zoom);
c.strokeStyle = '#fff';
c.stroke();
that.prevx = that.x;
that.prevy = that.y;
that.x += 0.1;
that.y = func(that.x);
}
function animate() {
requestAnimationFrame(animate);
draw();
}
animate();
}
plot(Math.sin);
plot(Math.cos);
Вы можете сделать то же самое, используя метод «привязки» при вызове функции. Это изменит ключевое слово this в этой функции, чтобы оно ссылалось на переданный объект.
var x = 0;
var y = 0;
var prevx = 0;
var prevy = 0;
var zoom = 25;
function plot(func) {
this.func = func;
this.x = x;
this.y = y;
this.prevx = prevx;
this.prevy = prevy;
this.draw = () => {
c.beginPath();
c.moveTo(this.prevx * zoom, this.prevy * zoom);
c.lineTo(this.x * zoom, this.y * zoom);
c.strokeStyle = '#fff';
c.stroke();
this.prevx = this.x;
this.prevy = this.y;
this.x += 0.1;
this.y = func(this.x);
}.bind(this)
this.animate = () => {
requestAnimationFrame(this.animate);
this.draw();
}.bind(this)
this.animate();
}
plot(Math.sin);
plot(Math.cos);
Я почти уверен, что все ваши ключевые слова
thisв этом коде (кроме вызововc.lineTo(...)и т. д.) На самом деле указывают на глобальный объект. Так что неудивительно, что свойства перезаписывают друг друга.