17
var tools = {};

tools.triangle = function() {
    var originX = 0;
    var originY = 0;
}

 

var tools = {};

tools.triangle = function() {
    this.originX = 0;
    this.originY = 0;
}

Are there any differences between these two code blocks? Sorry if this has been asked before.

2
  • 1
    var variable is private. this variable is public. Commented Jul 1, 2012 at 22:08
  • 2
    @elclanrs—that comment is unhelpful because it is misleading. Variables can be declared as globals, this is related to execution context, it is not a variable in the usual sense, though it can be considered a local variable. Commented Jul 1, 2012 at 23:51

2 Answers 2

13

var creates a local variable within tools.triangle. The variables originX and originY cannot be interacted with outside of tools.triangle. this is a pointer to the current object you are dealing with. The second example can be used to give properties to an object by doing new tools.triangle();. If you do not use new and just use tools.triangle();, this will point the global object which is the window object. You can change the object to which this points by using the function methods call(); and apply(); like this:

var myObj = {};

tools.triangle.call( myObj );

// "this" in tools.triangle now points to myObj
// myObj now has the properties originX and originY

It is important to know that this can reference any object, as well as be undefined or null in ES5 strict mode.

You can find more information here.

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

3 Comments

this needs more explanation than provided, it is set by the call and can reference any object, as well as be undefined or null in ES5 strict mode.
@0x499602D2 Thank you for your answer. I really was looking for this. I also wasn't aware of the fact that the call(and apply) method could change the scope.
The answer needs correction around the scenario when new is not used. Since triangle is an instance function of tools object, this points to tools object and calling tools.triangle() will actually create the properties originX and originY on the tools object.
1

In the first example, X and Y both exist as local variables to the closure saved in the variable triangle.

In the second example, X and Y exist as variables to the object tools.triangle because of the use of this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.