blisher
blisher

Reputation: 75

Angular - Should I use local variable or this.variable

I was looking for this but could not find a question as simple as I want it. The problem is really simple: In angular js, should I use local variables, or properties of this (in cases when I don't need to use this).

Example:

// I need "this" here because I need this collection in template
this.collection = SomeService.fetchCollection();

// I can use either "foo" or "this.foo" here, which one is better?
this.fetchSomeData = function(type) {
    var foo = AnotherService.foo(type);
    return FooService.call(foo);
}

Upvotes: 0

Views: 292

Answers (3)

JSFrank
JSFrank

Reputation: 13

Because you haven't declared 'foo' as a var it will be a global here, which is bad. You should at least prefix it with 'var' so it's scoped to the function and not globally; it shouldn't be available outside the function.

Upvotes: 1

pwolaq
pwolaq

Reputation: 6381

in my opinion it is a good practice not to reveal everything and keep it encapsulated - for example, it avoids moving logic to view which is bad

also, consider that you have a for loop iteration over i variable - would you also use this.i for such purpose?

Upvotes: 0

C14L
C14L

Reputation: 12548

A local variable, so it can be cleaned up as soon as the method exits. Otherwise it would stay unused in the parent's namespace.

But in 99% of cases that will have no real-world effect, so it doesn't matter.

Upvotes: 1

Related Questions