为什么两个波(或函数)相互干扰?

时间:2018-12-01 14:00:57

标签: javascript

我正在编写一个函数以在JS中绘制图形。在这里:

div

为什么即使我使用 this 关键字,这两个功能也会相互干扰?

该网站本身已经存在许多类似的问题,但我仍然无法获得答案,因此我在这里提出了要求。

谢谢!

1 个答案:

答案 0 :(得分:0)

在函数中使用“ this”关键字时,它表示函数本身。当您在“绘图”功能内部时,希望它在此引用“绘图”功能。您可以通过在“绘图”函数中创建一个新变量并使用它来实现。即“那个”。

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);

调用函数时,可以使用“ bind”方法执行相同的操作。这将更改该函数中的“ 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);
相关问题