M_x_r
M_x_r

Reputation: 604

Objects and variables in Javascript

Ok so imagine I have the following object

var House= function(){
    var color = "#0000FF";
}

Then I add the following method:

House.prototype.drawHouse = function(){
    document.write("House " + this.color);
    // ^^ How do I reference the color property of the object?
}

How is the best way to reference the color attribute from the drawHouse method?

Upvotes: -1

Views: 50

Answers (1)

zerkms
zerkms

Reputation: 254886

You cannot.

var color is a local variable, whose visibility scope is only limited by the anonymous function body.

You need to implement it like:

var House= function(){
    this.color = "#0000FF";
}

And after that you'll be able to access it via this.color in a drawHouse()

Upvotes: 7

Related Questions