Andy
Andy

Reputation: 65

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:

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:

var ctx = document.getElementById('theCanvas').getContext('2d');    
var blue = '#9ec3de';
res08(ctx, blue);
console.log( res08.color );

But that's returning undefined. I also tried declaring the function as a variable:

var res08 = function(ctx, color){

What am I missing? Thanks!

Upvotes: 0

Views: 67

Answers (3)

Joeytje50
Joeytje50

Reputation: 19112

You should instead use it as a class, calling it via a new keyword: 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.

Upvotes: 1

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123433

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 foo() {
    console.log(this);
}

foo(); // [object Window]

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

this refers to the context, not to the calling function. You can either call your function like this:

res08.call(res08, ctx, blue);

Or change your this.color = color line to this:

arguments.callee.color = color;

Or your console.log line to this:

console.log( ctx.fillStyle );

There are a number of options ;)

Upvotes: 0

Related Questions