这是如何工作的:
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:意外的标记。
):
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 .
A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).
Starting with JavaScript 1.5, you can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the \uXXXX Unicode escape sequences as characters in identifiers.
关于JavaScript 分配自变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23358097/