JavaScript赋值自变量
这是如何工作的:JavaScript赋值自变量,javascript,Javascript,这是如何工作的: function Test() { this.t=function() { var self=this; self.tutu = 15; console.log(self); } } var olivier = new Test(); function Test() { this.t=function() { var self = this, other = -1
function Test() {
this.t=function() {
var self=this;
self.tutu = 15;
console.log(self);
}
}
var olivier = new Test();
function Test() {
this.t=function() {
var self = this,
other = -1;
self.tutu = 15;
console.log(self);
}
}
var olivier = new Test();
这项工作:
function Test() {
this.t=function() {
var self=this;
self.tutu = 15;
console.log(self);
}
}
var olivier = new Test();
function Test() {
this.t=function() {
var self = this,
other = -1;
self.tutu = 15;
console.log(self);
}
}
var olivier = new Test();
这不起作用(错误为SyntaxError:Unexpected token.
):
var
语句用于声明变量。因此,您试图定义一个名为self.tutu
的变量,该变量在JavaScript中无效,因为变量名称中不应包含
。这就是它因语法错误而失败的原因
SyntaxError: Unexpected token .
引用
JavaScript标识符必须以字母、下划线(_)或美元符号($)开头;后续字符也可以是数字(0-9)。因为JavaScript是区分大小写的,所以字母包括字符“A”到“Z”(大写)和字符“A”到“Z”(小写)
从JavaScript 1.5开始,您可以使用ISO 8859-1或Unicode字母,例如标识符中的å和ü。您还可以使用\uxxx Unicode转义序列作为标识符中的字符
var
只能用于声明变量,但不能在表达式之前使用
var self.tutu=15代码>无效。最后一个模式不起作用,因为您正在变量声明块内创建self
的属性。您可以将代码重写为:
var self = (this.tutu = 15, this),
other = -1;
/* self = (this.tutu = 15, this) =>
(,) creates a group. Using the comma operator,
the statements within the group are evaluated from
left to right. After evaluation self is a reference to this
and this now also contains the property tutu */
与此非常相似:
根据这个答案,您实际上在这样做:var self=(window.other=(self.tutu=15))
,这当然会给出语法错误,因为您试图在self
存在之前分配self.tututu
我不确定有没有办法用这种方式做平行作业,但是当然
var self = this;
var other = -1;
self.tutu = 15;
将很好。如果我尝试self['tutu']
这是同样的问题。@OlivierPons是正确的,因为变量声明中也不允许[
,'
和]
。@OlivierPons在其他两个示例中,您正在为对象的属性赋值,但在上一个示例中,您试图创建一个标识符中包含无效字符的变量:var a={t:15},b=a.t代码>和这个:vara={t:15},b=a['t']代码>。这对我很有用Chrome@OlivierPons在这种情况下,变量名只是a
和b
。价值观可以是任何东西。例如,尝试vara={t:0},a.t=15代码>,它将失败。因为变量名a.t
有问题,所以我不想在self存在之前分配“self.tutu”。在Javascript中,您可以这样做:vara={t:15},b=a.t代码>而且它工作完美无瑕,这与我的要求非常相似。