Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Class name mangled after minification #2052

Closed
wuyuntao opened this Issue · 51 comments
@wuyuntao

JavaScript minification tools rename local functions for performance, and this mangles CoffeeScript class names too.

Since Function.name is a read-only property, forcing class names which implemented in #494 does not work.

How about setting class name to some other property, like Foo.__name__ or Foo.className?

A brief example

class Foo
  constructor: ->
    console.log(this.constructor.name)

foo = new Foo()

Compiles into

(function() {
  var Foo, foo;
  Foo = (function() {
    Foo.name = 'Foo';
    function Foo() {
      console.log(this.constructor.name);
    }
    return Foo;
  })();
  foo = new Foo();
}).call(this);
// Outputs 'Foo'

Minified

(function(){
  var a,b;
  a=(function(){
    a.name='Foo';
    function a(){
      console.log(this.constructor.name);
    }
    return a;
  })();
  b=new a();
}).call(this);
// Outputs 'a'
@michaelficarra
Collaborator

I would be in favour of Foo.name = Foo.displayName = "Foo" compilation.

@kitcambridge

Something to consider: (function self(){ "use strict"; self.name = self.displayName = "foo"; }()) will raise a TypeError. I don't think there are too many cases where compiled CoffeeScript code would be combined with strict mode JS code, but it's something to be aware of.

@michaelficarra
Collaborator

@kitcambridge: Huh. That's interesting, since we're already assigning the name property currently. Maybe we should just change it to Foo.displayName = "Foo" then.

edit: We could additionally include if(!__hasProp(Foo, 'name')) Foo.name = "Foo";, but I don't think I would support that.

@inossidabile

Assigning .name property would be very confusing since this leads to different behavior in IE and other browsers. It's especially notable when everything stops working right after auto-minification on the production.

IMHO the current fix on #494 make the situation way worse then it was before. With that you have even more chances to stuck into reality much too late.

My vote goes to __name__. I trust you should not pollute base class naming. I can easily imagine "displayName" as a field I'd like to use myself. Same goes to className. __notation__ is well known for such kind of hacks and will do the job very well.

@jamesmacaulay

My vote goes to __name__

+1. Or possibly just __name, to go along with __extends et al.

@benatkin

@jamesmacaulay Good thinking, but I think it goes along more with __super__ than with __extends, so it should be called __name__. Though __name would probably have less chance of conflict...

@jashkenas jashkenas was assigned
@michaelficarra
Collaborator

@jashkenas: do you have enough information to make a decision for us here?

@jashkenas
Owner

Ugh -- this is bad news. I now wish I had stuck to my guns on #494, and left forced class names out. Let's remove them at our nearest convenience.

@michaelficarra
Collaborator

@jashkenas: Do you want to define an alternative property or just remove it entirely?

@jashkenas
Owner

I'd like to remove it entirely. If you want to tag a name on your class -- tag a name on your class yourself.

@michaelficarra
Collaborator

Sure thing. I'll get on it.

@devongovett

NOOOOOOOOO! Such a useful feature! Can't we just go with .displayName or something else? :) displayName is already used by developer tools to display names of functions in the profiler, and I'm pretty sure other langs like Objective-J compile that too... Pretty please? :P

@jashkenas
Owner

Nope. You can already see the name of the function in any decent debugger.

@devongovett

Probably. But I use the name feature for other reasons, as detailed in #494 by myself and @hornairs such as automatically figuring out the REST url for a resource from the class name. Pretty soon we're gonna have to start writing extensions to CoffeeScript to get the useful features that keep getting rejected, like this and the extended hook. :(

@michaelficarra michaelficarra closed this issue from a commit
@michaelficarra michaelficarra fixes #2052: don't manually assign constructors' `name` property
I'm not sure how we would test this, so... no tests.
f3a1f46
@michaelficarra
Collaborator

Fixed.

@jashkenas: It seems like this issue is affecting a lot of our users. Time to cut another bugfix release?

@inossidabile

Ah :(. Really bad news. We've been waiting for this so much time and now it will never happen :scream:

@jashkenas
Owner

It seems like this issue is affecting a lot of our users.

... I wasn't getting that sense -- I think it's only a problem if you're intentionally strict-mode-ing your CoffeeScript ... which you certainly don't have to do. Let's wait a reasonable interval before the next bugfix point release.

@domenic

Just lending my support to backing out the assignment. Function#name already has a meaning, and messing with it is a bad idea.

@michaelficarra
Collaborator

@jashkenas: See #2249, #2250. Within 24 hours, we've already had 2 issues opened. At this rate, we'll have over a dozen by next week :trollface:.

@domenic

Indeed, new release please; cannot upgrade until this is fixed. Another example.

@jashkenas
Owner

Let's shoot for a stable one tomorrow afternoon then.

@satyr
Collaborator

f3a1f46 fixes #2052

That fix is for #2050#2250, which isn't really a duplicate of this.

Marking this wontfix for now.

@michaelficarra
Collaborator

@satyr: #2050 is a pull request for line mappings. Now I'm confused.

@satyr
Collaborator

Er, sorry. I meant #2250 there.

@michaelficarra
Collaborator

Alright, agreed. This is a wontfix since we're not going to assign a string containing the name to some special property, and f3a1f46 actually fixes #2249 and #2250.

@michaelficarra
Collaborator

@jashkenas: ping.

@paulmillr

@jashkenas not using any constructor.name analog is a bad desicion.

You may know coffee direction better, but let me explain: there are great real-world use-cases of the feature, backbone classes.

1.3.1 (real production code):

View = require './view'

module.exports = class TweetView extends View
  tagName: 'article'

It will auto-add className: 'tweet' and template: require './templates/tweet'. Convention over configuration, ya know.

Situation on the current master is pretty shitty:

View = require './view'

module.exports = class TweetView extends View
  __name__: 'TweetView'  # etc. No DRY.
  tagName: 'article'

When you were adding the feature, you've said:

Our classes have grown fancier over time. Before they were little more than .prototype = object literal ... now, they're fully executable, with super tricks, static "inheritance" (via copying), named constructors, etc etc. This is just a bit of a further progression towards making them comfy.

and I completely agree with this. Classes allow to build great apps. So why no auto-add @constructor.__name__ etc to them?

@jamesmacaulay

Yay! An implementation :) Thanks @paulmillr!

One of CoffeeScript's biggest advantages is that it fixes a bunch of annoying things about JavaScript: it makes vars always local, equality always strict, switch statements auto-break, etc.

It seems pretty clear-cut to me that Function.name is broken, at least in practical terms. Unless you want to deliver uncompressed JS, you just can't use it at all. And if you tweak your JS compressor to keep function names intact, it ends up resulting in a sub-optimal compression. I see this as the perfect kind of problem for CoffeeScript to provide a solution.

@domenic

@jamesmacaulay Function.name isn't part of JavaScript; it's a vendor-specific extension. It's outside the scope of CoffeeScript to fix vendor-specific extensions, from what I understand.

@paulmillr

@domenic yea, and we're not fixing them, if we'll use my pull request. We'll just add new functionality. @constructor.name breaks minifiers and is read-only so it's unreliable.

@jamesmacaulay

@domenic fair enough. I'm not arguing that CoffeeScript is "breaking promises" here, though; just that this is a great opportunity to fill an obvious gap.

@wuyuntao

I totally agree with @paulmillr and @jamesmacaulay.

Class names are widely used in MVC. Model names are used as names of db tables. Controller names are used in URL routing. Views as @paulmillr metioned could generate css classes and template names from their class names.

It could be a great loss if we cannot use them in CoffeeScript classes.

@jashkenas
Owner

@michaelficarra -- What's the "ping" regarding? Aren't we settled on this?

@michaelficarra
Collaborator

Let's shoot for a stable one tomorrow afternoon then.

But it seems now that a lot of people don't want the change that's currently on master, so it's your call. I think @paulmillr's pull request is reasonable.

edit: Oh, it looks like you just turned that down. We should push out another bugfix release, then.

@jashkenas
Owner

Let's shoot for a stable one tomorrow afternoon then.

Hah. Got away from me...

I really don't want to mint new "name" semantics that are special for CoffeeScript classes. I think it'll end in tears.

@michaelficarra
Collaborator

That's entirely reasonable. Are you planning on pushing the release that removes the name assignment soon? There's 1 or 2 other fixes on master as well.

@jashkenas
Owner

Yep -- and maybe bringing a few other tickets along for the ride. I'm glad that nothing else pressing has come up over the weekend, apart from "use strict".

@bennedich

Would somebody mind uploading this fixed version to npm?

@michaelficarra
Collaborator

@bennedich: as soon as a new release is pushed. See #2282.

@aseemk

Great points @wuyuntao. I agree wholeheartedly.

( #2052 (comment) )

@maccman

Agree with @wuyuntao - class names are incredibly useful (used all over the place in Spine, for example). The only issue here is that the standards committee made the wrong call by making .name readonly. I think .displayName would suffice, and wouldn't necessarily lead us down a slippery slope of polluting classes.

@marcandre

Add me to the camp of "give me access to my class name". I like constructor.className as it is very descriptive.

@paulwittmann

very confused about the status of this. is it still a wontfix or has it already been fixed as jeremy and paul's comments here (#2262) seem to suggest?
i'm using rails 3.2.6 with coffee-script-2.2.0, coffee-script-source-1.3.3, and coffee-rails-3.2.2 - and still get .name errors when using strict mode =(

@jashkenas
Owner

CoffeeScript has removed the additional setting of the .name property on classes ... because of strict mode.

@marcandre

CoffeeScript has removed the additional setting of the .name property on classes

Any plan to add constructor.className or similar? Are there reasons against it?

@jdickey

Certainly on our project, it would simplify some otherwise-gnarly code dramatically; I'm sorry, but the tediousness and likelihood of errors scales up far more rapidly than the number of classes involved in a non-trivial hierarchy. If you're being a Good Little Scripter™ and making extensive use of private vars/methods, sticking an extra, public "Hi! My Name is FooClass!" sticker on to cover a weakness in the language just Feels Very, Very Wrong™. And it really doesn't matter if the "weakness" is in CoffeeScript's layer or the underlying JS-in-strict-mode; enough people have expressed enough pain induced by this that we need to find a solution. Our project's "workaround" looks to be moving as much current front-end Script functionality as possible to the back-end Ruby code and just hitting the network much more than we are now, which has implications that should be quite foreseeable. I'm already short two developers; we don't have the time to grok the source and fix it ourselves, and even if we did, our fix would be too unlikely to be compatible with what @jashkenas or others in the community come up with simply because we don't have the same level of expertise.

So where do we go from here?

@danschumann

At some point coffeescript will become too big to please everyone, right? Well, it's probably too late for that already. What about a config file that allows you to toggle on or off some options like this one, since I think a lot of people are for it, even if a lot are against it, why not make that a simple true false in a compiler.conf? I'm on the side for it by the way, since I don't want minifying my code to break any lazy references I've made to classes, and developers here are lazy and referencing classes in such a way, and I don't blame them. If you make a class, that class should know what it is made of in a reliable fashion. I have 98 more cents to spend, anyone have any gum?

@michaelficarra
Collaborator

@danschumann: This is no longer a problem when using CoffeeScriptRedux's source maps.

@danschumann

@michaelficarra So.. what's with the original coffeescript then? Is it moving to become the redux coffescript 2, or are they both being maintained in parallel? Is it easy to use the customization options? The readme on cs2 doesn't seem to say anything.. what's the difference and what do I have to read?

@davej davej referenced this issue in ahmednuaman/radian
Closed

Cleaner controller class syntax #16

@tony-kerz tony-kerz referenced this issue in michaelficarra/CoffeeScriptRedux
Open

question: will you be re-introducing <class>.name? #302

@vitalyiegorov vitalyiegorov referenced this issue from a commit in samsonos/php_coffeescript
@bfanger bfanger Fixes TypeError for classes in FF strict mode.
"Due to the new semantics of JavaScript's strict mode, CoffeeScript no longer guarantees that constructor functions have names in all runtimes. See #2052 for discussion."

jashkenas/coffeescript#2052
247cd8c
@trabianmatt trabianmatt referenced this issue from a commit in trabian/trabian-webapp-core
@trabianmatt trabianmatt Use something other than the class name as the IdentityCache key
I was seeing some odd behavior when using a minified version of the js
on a project that leveraged the IdentityMap. It was caused by the use of
the class as the cache key -- js hashes only support string-based keys
so the toString() of the class constructor was being used as the hash
key.

This was fine (though inefficient) until the minification tool reused
function names when they weren't in the same scope (which is fairly
common when using CommonJS). A similar issue was covered in
jashkenas/coffeescript#2052.

This was solved in our case by assigning a unique CACHE_KEY property to
the class the first time it requests its cache. **Be aware, however,
that if you extend a class that already has a CACHE_KEY then it will use
that existing class's CACHE_KEY and therefore will mix IdentityCache
entries.** You can explicitly add a CACHE_KEY class property to avoid
this situation.
4532d7b
@CyborgMaster

Sorry to bump such an old thread, but I had a few questions. I am working on a project where we need to get a hold of the class name. We are building some features into our models for auto-configuration (convention over configuration), where the names of id properties, json urls, etc. are intuited from the model class name (similar to what Rails does).

What is the current official recommendation from coffeescript on how to do this? I loved the name property that was added to constructors, but based on this thread, that seems to have been removed. I also loved the idea of __name__ to handle minification and browser support issues, but that also seems to have been rejected.

Is the current recommendation to simply add another property on the class manually? Something like this?

class Foo
  @name: 'Foo'

That works, but it certainly isn't very DRY.

If the manual class property is all we've got then I will use it of course, but I just wanted to check what the official recommendation was.

Sorry if this was the wrong place to ask. I thought about opening a new issue, because this one is so old, but it seemed like the correct thread. If there is a better place to ask let me know and I can repost and do better in the future.

Thanks!

@epidemian

@CyborgMaster you can assign the class to some object's property:

class Models.Cat
  talk: -> 'meow'

# Or...
Models.Cat = class 
  talk: -> 'meow'

# Or...
@Cat = class
  talk: -> 'meow'

That way, you can trust that the name will be preserved upon minification because you've assigned it to a named property on an object, and not just a local variable.

Don't take this for an "official recommendation" though. It's just what i would do to keep a mapping between classes and some names. I hope it helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.