0

For using a static variable in javascript functions I found out two ways, using . and : operator. When using . operator we have to specify variable with "f.variable" and when using : we have to use "this.variable". what is the difference between the usage of these two operators.

function f(){
  f.a += 1;
  this.b += 1;
  console.log("f.a: ", f.a);
  console.log("this.b: ", this.b);
}
f.a = 0;
f:b = 0;

also we cannot use : when using that variable outside its function like:

function g(){
  f:b = 0; //this works fine.
  var c = f:b; //raises error invalid label.
  console.log(f:b);//but this raises an error missing ')'.
}

Same is the case when we use var to create objects.

var obj = {
 a: 2,
 b: 3
}
//accessing a and b is done using obj.a & obj.b
//but here
obj:a = 4;
console.log(f.a); // this gives 2
//and similarly using obj:a as rhs value gives error.

How are these two operators used actually.

EDIT: What is the difference between these two types of variables created.

1
  • 1
    you should not use f:b = 0; notation. The syntax is correct but the meaning is not. Use var b = 0; for variable and var o = { b:0 }; for object
    – pomeh
    May 18, 2012 at 13:36

1 Answer 1

3

This:

f:b = 0;

is interpreted as a label, "f", before an expression statement, b = 0;. The ":" is used in object literal syntax to separate a property name expression from its value expression. Otherwise, it is not used for referring to properties of objects.

6
  • +1 Good answer. I think that labels are only accessible within the scope they are defined; that is an assumption I am making since I rarely, if ever really, use labels in my code. If I were a better person I would create a test for this to find out for sure. May 18, 2012 at 13:38
  • I am curious. Can someone tell me why 'console.log(f:b)' generates raises an error missing ')'?
    – user753137
    May 18, 2012 at 13:42
  • @DanielK. it's because the parser guesses that you meant to type console.log() f:b ... or something like that. In other words, the "f:" is meaningless in that context, so it assumes you forgot to finish the previous expression before starting a new statement.
    – Pointy
    May 18, 2012 at 13:47
  • but what type of variable it creates for that function and how is it different from f.b = 0;
    – rajan
    May 18, 2012 at 13:52
  • 1
    @rajan just never use ":" unless you're writing an object literal. It never makes sense outside of that context.
    – Pointy
    May 18, 2012 at 14:02

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.