You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue.js中实现function prototype并正确访问父级变量

问题根因

核心错误是你将Shape构造函数定义为了箭头函数:

  • 箭头函数没有独立的this绑定,其内部的this继承自外层作用域,不会指向你创建的类实例
  • 箭头函数不能作为构造函数使用,用new关键字调用时不会生成对应的实例对象
    所以你在构造函数里给this.x赋值的时候,根本没有挂载到Shape实例上,后续原型方法调用时自然读取不到this.x的值。

修复方案

方案1:将构造函数改回普通函数

直接把构造函数的箭头函数写法替换为普通函数声明即可,其余原型方法代码不需要改动:

// 仅修改构造函数为普通函数
exports.Shape = function(x1, y1, w1, h1, fill1) {
    this.x = x1 || 0;
    this.y = y1 || 0;
    this.w = w1 || 1;
    this.h = h1 || 1;
    this.fill = fill1 || '#AAAAAA';
};

exports.Shape.prototype.draw = function(ctx, Obj) {
    ctx.fillStyle = '#FF00FF';
    ctx.fillRect(50, 50, 50, 50);

    ctx.fillStyle = this.fill;
    ctx.fillRect(this.x, this.y, this.w, this.h);

    ctx.fillStyle = '#AAAAAA'
    ctx.fillRect(this.x + 10, this.y + 10, this.w - 20, this.h - 20, 20);
}

exports.Shape.prototype.contains = function(mx, my) {
    return (this.x <= mx) && (this.x + this.w >= mx) &&
        (this.y <= my) && (this.y + this.h >= my);
};

方案2:使用ES6 Class语法(更推荐)

现在前端项目更推荐用原生class语法实现类,逻辑更清晰,也不会出现this绑定的低级错误:

class Shape {
  constructor(x1, y1, w1, h1, fill1) {
    this.x = x1 || 0;
    this.y = y1 || 0;
    this.w = w1 || 1;
    this.h = h1 || 1;
    this.fill = fill1 || '#AAAAAA';
  }

  draw(ctx, Obj) {
    ctx.fillStyle = '#FF00FF';
    ctx.fillRect(50, 50, 50, 50);

    ctx.fillStyle = this.fill;
    ctx.fillRect(this.x, this.y, this.w, this.h);

    ctx.fillStyle = '#AAAAAA'
    ctx.fillRect(this.x + 10, this.y + 10, this.w - 20, this.h - 20, 20);
  }

  contains(mx, my) {
    return (this.x <= mx) && (this.x + this.w >= mx) &&
        (this.y <= my) && (this.y + this.h >= my);
  }
}

exports.Shape = Shape

额外注意

创建Shape实例时必须使用new关键字调用,示例如下:

const myShape = new Shape(0, 0, 200, 200, '#FF0000')
myShape.draw(ctx) // 此时this指向myShape实例,可以正常读取x、fill等属性

内容的提问来源于stack exchange,提问作者Ihor Matlak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 22:54:05