If I want to use the following in JS, Is some option available to do it?
var break = "";
In C# we have the option to use it using #, is similar option available in JS
public int #public;
Well, if you insist, you can
var $break = 1;
which is the same as C# in terms of characters ;)
Seriously, you cannot use reserved keywords as variables, but they are allowed as property names:
myObj = {}
myObj.break = 'whatever';
Also, do note that the repertoire of the reserved words varies depending on the strictness. For example,
var interface = 1;
is valid in the non-strict mode, but breaks once you add use strict to your script.
You can't use Javascript keywords as a variable name.
Related
I have this simple object:
var apple = {
type: "macintosh",
color: "red",
getInfo: function(int){
return "test" + int;
}
}
In Jmeter I want to put this object into a global variable that allows me to access this object.
I tried:
vars.putObject("test",apple); (In a pre-processor, so before all the assertions)
var test = vars.getObject("test"); (In all the assertions)
But it seems that the function is casted as string and therefore I can't use it in my assertions.
How to make this work?
If you are looking for a "global" solution you need to consider JMeter Properties instead of JMeter variables, to wit use props shorthand instead of vars. As per Sharing Variables user manual chapter:
The get() and put() methods only support variables with String values, but there are also getObject() and putObject() methods which can be used for arbitrary objects. JMeter variables are local to a thread, but can be used by all test elements (not just Beanshell).
If you need to share variables between threads, then JMeter properties can be used
For example in one test element:
props.put('test', apple)
In another one (can be in another Thread Group as well)
var apple = props.get('test')
log.info(apple.getInfo(1))
Also be aware that starting from JMeter 3.1 it is recommended to use Groovy language for any form of scripting as Groovy performance is much better than other scripting options, check out Apache Groovy - Why and How You Should Use It guide for more details.
In JMeter you can use Java language which you can add Object apple
public class apple {
String type = "macintosh";
String color = "red";
public String getInfo(){
return "test";
}
};
var a = new apple();
vars.putObject("a",a);
And get it later and use its methods:
var a = vars.getObject("a");
log.info(a.getInfo());
Also you can create Java classes with groovy
Crockford's JavaScript: The Good Parts contains the following text.
Reserved Words
The following words are reserved in JavaScript:
abstract boolean break byte case catch char class const continue
debugger default delete do double else enum export extends false final
finally float for
function goto if implements import in instanceof int interface long native new null
package private protected public return short static super switch synchronized this
throw throws transient true try typeof var volatile void while with
Most of these words are not used in the language.
They cannot be used to name variables or parameters. When reserved
words are used as keys in object literals, they must be quoted. They
cannot be used with the dot notation, so it is sometimes necessary to
use the bracket notation instead:
var method; // ok
var class; // illegal
object = {box: value}; // ok
object = {case: value}; // illegal
object = {'case': value}; // ok
object.box = value; // ok
object.case = value; // illegal
object['case'] = value; // ok
Some of the reserved words appear to not be reserved in my installed interpreters. For example, in both Chrome 48 (beta) and node.js 0.10.40 the following code will successfully add two numbers identified by reserved words.
var abstract = 1;
var native = 1;
abstract + native;
> 2
Why can I use these two reserved words as variable names? Am I missing something crucial?
Reserved keywords as of ECMAScript 6
break case class catch const continue debugger default delete do else
export extends finally for function if import in instanceof new return
super switch this throw try typeof var void while with yield
and abstract and native (more here) were reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3).
always reserved : enum
reserved when they are found in strict mode code:
implements package protected static let interface private public
reserved when they are found in module code: await
A reserved word (also known as a reserved identifier or keyword) is a word that cannot be used as an identifier, such as the name of a variable, function, or label – it is "reserved from use". Reserved words or keywords have special meaning within the programming languages. They are use to identify the data types in language that supports the system, which identify the blocks and loops, etc. so their functionality is is already defined in the system library.
Including keywords or reserved words in your code, create confusion to other developers as well as the compiler at the time that you run your code. That is why reserved words is not allow for many programming languages. There are some other programming language that have similar keywords; such as C, C++, C#, and Java they share a commonality.
Here you can get the most updated list of Reserved Words in JavaScript, it also contains useful examples.
I find myself, for reasons which are too irrelevant to go into here but which involve machine-generated code, needing to create variables with names which are Javascript reserved words.
For example, with object literals, by quoting the keys if they're invalid identifiers:
var o = { validIdentifier: 1, "not a valid identifier": 2 };
Is there a similar technique which works for simple variable references?
A poke around the spec shows that there used to be a mechanism that allowed this, by abusing Unicode escapes:
f\u0075nction = 7;
However this seems incredibly dubious, and is apparently rapidly vanishing (although my recent Chrome still appears to support it). Is there a more modern equivalent?
If they're object keys, you can call them what you like (even reserved names), and you don't need to quote them.
var o = { function: 'a' }
console.log(o.function) // a
DEMO
Is there a more modern equivalent?
No. Reserved words cannot be used as variable names. You can use names that look like those words but that's it.
From the spec:
A reserved word is an IdentifierName that cannot be used as an Identifier.
FYI, reserved words can be used as property names, even without quotes:
var o = { function: 1 };
Variable names can't be reserved words.
You can always do bad things like:
window["function"] = 'foo';
console.log(window.function);
> foo
You still can't reference it using a bare reserved, because it's reserved.
That it's machine-generated code means whatever is generating the code is broken.
I have this JS code:
var A = {};
A.new = function(n) { return new Array(n); }
It works well in all browsers, but when I try to obfuscate it with obfuscator, it shows an error.
Is it a valid JS code? I looked into specification, but didn't find anything. I know, that browsers sometimes accept syntactically wrong code, but I want to write syntactically correct code.
Note, that I am not doing var new = ...
BTW. what about this?
var a = { "new" : 2 }; // ok?
a.new = 3; // ok?
a["new"] = 3; // ok?
.
EDIT: Thank you all for your help! I wrote an email to obfuscator's authors and they fixed it! :)
Yes, your code is valid an the obfuscator is wrong (or old). new is a reserved word, that means it is not a valid identifier (e.g. to be used as a variable name). Yet, it is still an IdentifierName which is valid in object literals and in dot-notation property access.
However, this was not the case in EcmaScript 3, where both of these needed to be Identifiers, and keywords like new were invalid. Therefore it is considered bad practise to use these names unquoted in scripts on the web, which might be executed by older browsers.
Reserved words can be used as property identifiers:
A.new = 1
B = { function: 123 }
D.if = { else: 5 }
etc - it's all valid (not necessarily good) javascript.
These things are called "IdentifierName" in the specification, and the only difference between an "IdentifierName" and a regular Identifier is
Identifier :: IdentifierName but not ReservedWord
http://es5.github.io/#x7.6
I see no errors. Lead by a dot its just a property name, just like ['new'], not any more a reserved word.
Since new is a reserved word, it can't be used as an identifier, although it can be used as an identifierName. See this section of the ECMAScript specification. So your code is legal, and apparently the obfuscator doesn't understand this distinction.
To work around this, you can access it using array-style notation:
A['new'] = function(n) { return new Array(n); };
in the beginning i declare a variable like this:
var content = "likes";
var main_likes_data = true;
And later i want to change the variable to false, but i need to add a new variable like this:
main_" + content + "_data = false;
But this does not work!
Can someone please tell me the right sytax to change the variable?
Thank You!!!
You need an associative array.
var content = "likes";
var main_data = {
likes: true,
somethingelse: false,
xyz: false
};
main_data[content] = false;
window["main_" + content + "_data"] = true;
This works as
a) variables created without a defined scope are, by default, scoped against the window object
b) You can use the square bracket notation in javascript interchangably with the dot notation. The square bracket notation takes a string. The string can be concatenated using variables.
Live example: http://jsfiddle.net/bX5Zy/
It's really bad programming practice, but you could use eval:
eval("main_" + content + "_data = false");
I personally would not use eval myself, but other people would. To quote John Resig:
“Overwhelmingly [eval is] trivailized, misused, and outright condemned
by most JavaScript programmers but by looking at the work of some of
the best coders you can see that , when used appropriately [it] allows
for the creation of some fantastic pieces of code that wouldn’t be
possible otherwise”
John Resig, in Secrets of the JavaScript Ninja