-1

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?

1
  • This question is similar to: What is the scope of variables in JavaScript?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Dec 21, 2024 at 8:56

1 Answer 1

7

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()

Sign up to request clarification or add additional context in comments.

1 Comment

+1 thanks for the insight. Not sure why the question was downvoted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.