[英]Javascript: What is the difference between usage of . and : operators for specifying a variable in a function or object?
For using a static variable in javascript functions I found out two ways, using . 对于在javascript函数中使用静态变量的方法,我发现了两种使用的方法。 and : operator. 和:运算符。 When using . 使用时。 operator we have to specify variable with "f.variable" and when using : we have to use "this.variable". 运算符,我们必须使用“ f.variable”指定变量,而在使用时:我们必须使用“ 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创建对象时,情况也是如此。
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. 编辑:这两种类型的变量之间有什么区别。
This: 这个:
f:b = 0;
is interpreted as a label , "f", before an expression statement, b = 0;
在表达式语句之前, b = 0;
解释为标签 “ f” 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. 否则,它不用于引用对象的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.