0

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);
}

3 Answers 3

1

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.

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

Comments

1

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.

3 Comments

Oh I use coffescript on a daily basis hence I forgot about "var", it should be there
In that case it's fine. There's no need to add it to 'this' unless you're going to need it in another method later. To be honest I'd probably even inline it like so: return FooService.call(AnotherService.foo(type)); but some people might consider that bad practice.
inlining this case wouldn't create a spaghetti, but in some cases we need to handle much longer lines of code, and inlining them would create reallyyyy long line
0

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?

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.