5

Microsoft allows to set environment variables in JScript with the following syntax:

var sh = WScript.CreateObject("Wscript.Shell");
var env = sh.Environment("PROCESS");
env("TEST") = "testvalue";

I wonder about the third line - and with me JSLint, which calls this line a "Bad Assigment".

But it works!

Is it ECMAscript standard compatible to have a function's return value as an lvalue (like here)?

If yes: How would one write such a function?

VisioN
  • 143,310
  • 32
  • 282
  • 281
rplantiko
  • 2,698
  • 1
  • 22
  • 21
  • Cool! Please make that snippet (together with a link to the official docs) an answer to my [*Real world examples of a function returing a reference* question](http://stackoverflow.com/questions/13124417/real-world-examples-of-ecmascript-functions-returning-a-reference) – Bergi Sep 16 '13 at 23:07

1 Answers1

8

Yes, the standard permits functions to returns references. No, you cannot write such a function in Javascript. ;)

<...> the left-hand operand of an assignment is expected to produce a reference. <...> function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference. http://es5.github.io/#x8.7

georg
  • 211,518
  • 52
  • 313
  • 390
  • but what you can do is setting properties of the Object, the returned reference points to `ret("sth").someProp = "sth"` – Moritz Roessler May 22 '13 at 08:36
  • This was quick and exactly the answer I was looking for. Thank you. – rplantiko May 22 '13 at 08:39
  • 1
    @C5H8NNaO4: this doesn't mean `ret()` returns a reference. Reference is a pair `[base,prop]` and the function only evaluates the base part. – georg May 22 '13 at 08:39
  • 1
    @thg435 Yes, what i meant was sth like `var someObjs = [{a:"",someProp:"b"}]; (function (a) {return someObjs[a]})(0).someProp = "c";console.log(someObjs[0].someProp) //c` – Moritz Roessler May 22 '13 at 08:45
  • 1
    @C5H8NNaO4: Still, your IEFE there returns the `{a:"",someProp:"b"}` object on which then a property is set, it does not return a reference. – Bergi Sep 16 '13 at 23:13