如何在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
相关产品推荐
相关产品推荐

