简体   繁体   中英

Why || = not compiled such that if we use [] or not, in coffeescript?

why this difference:

class Foo
  getTest: ->
    @test ||= 42

compiled to:

return this.test || (this.test = 42);

different of

class Foo
  getTest: ->
    @test['bar'] ||= 42

is compiled in :

var _base;
return (_base = this.test)['bar'] || (_base['bar'] = 42);

what is the usefulness of this variable "_base"?!

return this.test['bar'] || (this.test['bar'] = 42);

is a good way too, no?

thx.

There are two broad categories of structures that ||= needs to consider:

simple_expr  ||= x
complex_expr ||= x

A simple expression would be something like @test : (probably) no side effects and (probably) no performance penalty to evaluating it twice.

A complex expression would be anything else: @test['x'] , @test(11).pancakes , ... Complex expression could have side effects or could be expensive so you only want to evaluate them once.

Now consider how many times expr1 is evaluated in:

expr1 || (expr1 = expr2)

Sometimes expr1 will be evaluated twice so CoffeeScript is stashing as much of expr1 as it can in _base to avoid the expense and possible side effects of evaluating expr1 twice.

You might also notice that for simple expressions, that only possible thing to stash in _base is the whole expression itself. I suspect that they're actually defaulting to considering all expressions complex and then leaving out _base when it turns out that there's nothing to stash in it.

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