JavaScript assigning self variable

How comes this works:

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

This works:

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

And this doesn't work (with the error SyntaxError: Unexpected token . ):

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

var statement is used to declare variables. So, you are trying to define a variable with name self.tutu , which is not valid in JavaScript, as variable names should not have . in their names. That is why it is failing with Syntax error.

SyntaxError: Unexpected token .

Quoting from 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.


var could only used to declare variables, but not before expression.

var self.tutu = 15; is not valid.


Pretty similar to this: Multiple left-hand assignment with JavaScript

Per that answer, you're actually doing this: var self = (window.other = (self.tutu = 15)) , which of course will give the SyntaxError, because you're trying to assign self.tutu before self exists.

I'm not sure there's a way to do parallel assignment in this way, but of course

var self = this;
var other = -1;
self.tutu = 15;

will work fine.

链接地址: http://www.djcxy.com/p/69988.html

上一篇: Javascript多重任务说明?

下一篇: JavaScript分配自变量