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;
        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 .

引用自Variables section in MDN ,

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/

相关文章:

javascript - 如何在 Bokeh 的回调中使用 cb_obj?

javascript - `await` 慢于 Chrome 中应有的速度

javascript - 如何不在文本字段中显示文本

javascript - 使用 Websockets 对 Vue.js/Node.js 应用程序进行单元测试

javascript - Protovis 比例交互线图示例

javascript - 如何使用空格键自动播放音乐并停止/继续播放?

javascript - Sentry JS 不会忽略全局错误

javascript - 在这样的元素中创建 jQuery 代码的目的是什么

javascript - 如何在 LI 中强制 DIV(带有溢出隐藏样式)仍然显示

javascript - 使用 jQuery 和 Ajax 提交表单