Javascript syntax need some explanation
I am reading Javascript the Good Parts and came across the following snippet under Chapter 5 Inheritance:
var coolcat = function (spec) {
var that = cat(spec),
super_get_name = that.superior('g开发者_运维技巧et_name');
that.get_name = function (n) {
return 'like ' + super_get_name() + ' baby'; return that;
}
}
I am confused by the coma after cat(spec) in line 2. What does the line do exactly? (line 2 +line 3) Thanks
That's just a shortcut for declaring two variables in one statement, it is equivalent to this:
var that = cat(spec);
var super_get_name = that.superior('get_name');
The comma is actually an operator in JavaScript:
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
A var
statement is made up of one or more expressions of the form:
varname [= value]
where the square brackets indicate an optional component. The general var
statement looks like this:
var varname1 [= value1 [, varname2 [, varname3 ... [, varnameN]]]];
You'll usually only see the comma operator used in var
statements and for
loops:
for(var i = 0, x = complicated_array[0]; i < complicated_array.length; x = complicated_array[++i])
but it can be used in other places.
It lets you declare another variable. It's equivalent to the following:
var that = cat(spec);
var super_get_name = that.superior('get_name');
See the var
statement docs @ MDC.
The indentation is wrong, it should be:
var that = cat(spec),
super_get_name = that.superior('get_name');
It is the same as saying:
var that = cat(spec);
var super_get_name = that.superior('get_name');
精彩评论