简体   繁体   中英

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.

The last pattern doesn't work because you are creating a property of self within the variable declaration block. You could rewrite your code to:

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 */

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM