[英]Javascript: using a function as an object and accessing properties
This is probably simple, but I'm not getting it. 这可能很简单,但我不明白。 I'm declaring a function to draw a shape on an html canvas like so:
我在声明一个在html画布上绘制形状的函数,如下所示:
function res08(ctx, color){
this.color = color;
ctx.save();
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(649, 143);
ctx.lineTo(649, 158);
ctx.lineTo(661, 158);
ctx.lineTo(664, 154);
ctx.bezierCurveTo(665, 155, 666, 157, 666, 158);
ctx.lineTo(683, 158);
ctx.lineTo(683, 144);
ctx.lineTo(674, 144);
ctx.lineTo(674, 137);
ctx.lineTo(678, 137);
ctx.lineTo(678, 111);
ctx.lineTo(648, 111);
ctx.lineTo(648, 143);
ctx.lineTo(649, 143);
ctx.closePath();
ctx.fill();
}
I thought because the function is an object that after it was called I would be able to access the color property like so: 我认为因为该函数是一个对象,因此在调用该函数后,我将能够像这样访问color属性:
var ctx = document.getElementById('theCanvas').getContext('2d');
var blue = '#9ec3de';
res08(ctx, blue);
console.log( res08.color );
But that's returning undefined . 但这返回的是undefined 。 I also tried declaring the function as a variable:
我也尝试将函数声明为变量:
var res08 = function(ctx, color){
What am I missing? 我想念什么? Thanks!
谢谢!
You should instead use it as a class, calling it via a new
keyword: new className()
. 您应该改为将其用作类,并通过
new
关键字: new className()
对其进行调用。 Here is a demo of how that would work. 这是一个如何工作的演示。 With your code, it would be something like this:
使用您的代码,将如下所示:
function res08(ctx, color){
this.color = color;
ctx.save();
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(649, 143);
ctx.lineTo(649, 158);
ctx.lineTo(661, 158);
ctx.lineTo(664, 154);
ctx.bezierCurveTo(665, 155, 666, 157, 666, 158);
ctx.lineTo(683, 158);
ctx.lineTo(683, 144);
ctx.lineTo(674, 144);
ctx.lineTo(674, 137);
ctx.lineTo(678, 137);
ctx.lineTo(678, 111);
ctx.lineTo(648, 111);
ctx.lineTo(648, 143);
ctx.lineTo(649, 143);
ctx.closePath();
ctx.fill();
}
var ctx = document.getElementById('theCanvas').getContext('2d');
var blue = '#9ec3de';
var res = new res08(ctx, blue);
console.log( res.color );
This works, because the this
keyword now refers to the variable res
. 之所以有效,是因为
this
关键字现在引用变量res
。
this
refers to the context, not to the calling function. this
是指上下文,而不是调用函数。 You can either call your function like this: 您可以像这样调用函数:
res08.call(res08, ctx, blue);
Or change your this.color = color
line to this: 或将您的
this.color = color
线更改为此:
arguments.callee.color = color;
Or your console.log
line to this: 或您的
console.log
行:
console.log( ctx.fillStyle );
There are a number of options ;) 有很多选择;)
You can refer to the function within its body by its name: 您可以在函数体内通过其名称引用该函数:
function res08(ctx, color) {
res08.color = color;
// ...
}
The context (value of this
) of a function
is rarely a reference to the function itself: function
的上下文( this
值)很少是对函数本身的引用:
function foo() {
console.log(this);
}
foo(); // [object Window]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.