JavaScript分配自变量

JavaScript assigning self variable

本文关键字:自变量 分配 JavaScript      更新时间:2023-09-26

这是如何工作的:

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 .):

function Test() {
    this.t=function() {
        var self  = this,
            other = -1,
            self.tutu = 15;
        console.log(self);
    }
}
var olivier = new Test();

var语句用于声明变量。因此,您试图定义一个名为self.tutu的变量,这在JavaScript中是无效的,因为变量名称中不应该有.。这就是为什么它由于语法错误而失败的原因。

SyntaxError: Unexpected token .

引用MDN、中的变量部分

JavaScript标识符必须以字母、下划线(_)或美元符号($)开头;后续字符也可以是数字(0-9)。因为JavaScript是区分大小写的,所以字母包括字符";A";通过";Z";(大写)和字符";a";通过";z";(小写)。

从JavaScript1.5开始,您可以在标识符中使用ISO8859-1或Unicode字母,如å和ü。您也可以使用''uXXXX Unicode转义序列作为标识符中的字符。

var只能用于声明变量,但不能在表达式之前声明。

var self.tutu = 15;无效。

与此非常相似:使用JavaScript 的多个左手分配

根据这个答案,您实际上正在执行以下操作:var self = (window.other = (self.tutu = 15)),这当然会给出SyntaxError,因为您试图在self存在之前分配self.tutu

我不确定有没有办法用这种方式进行并行分配,但当然

var self = this;
var other = -1;
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 */