[英]Prototype function vue.js
需要在Vue.js上實現一個function原型,第三天找不到怎么做。 從原型我無法到達“父”變量
function Shape(x, y, w, h, fill) {
this.x = x || 0;
this.y = y || 0;
this.w = w || 1;
this.h = h || 1;
this.fill = fill || '#AAAAAA';
}
Shape.prototype.draw = function(ctx) {
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);
}
Shape.prototype.contains = function(mx, my) {
return (this.x <= mx) && (this.x + this.w >= mx) &&
(this.y <= my) && (this.y + this.h >= my);
}
這是最接近目標的,但它繪制但看不到變量
exports.Shape = (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);
};
但是 this.x 是未定義的
我看不出你的第一個例子有問題嗎? 可以訪問變量,我將它們記錄在控制台中。
也許你忘了全局定義ctx
?
function Shape(x, y, w, h, fill) {
this.x = x || 0;
this.y = y || 0;
this.w = w || 1;
this.h = h || 1;
this.fill = fill || '#AAAAAA';
this.draw()
}
Shape.prototype.draw = function(ctx) {
console.log("variables of Shape:")
console.log(this.x)
console.log(this.fill)
}
let s = new Shape(30,30,30,30,"#EEF")
s.draw()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.