0

I'm working on an ActionScript 2 project that relied on some extensions to the Math class, usually done as such:

Math.sinD = function(angle) {
    return Math.sin(angle*(Math.PI/180));
};

Allowing a caller to just write (for example)

Math.sinD(60);

However, when I try to compile with just the original line, I get the following error: There is no property with the name "sinD".

Why isn't this working, and more importantly, how can I make it work again?

Jezzamon
  • 1,453
  • 1
  • 15
  • 27
  • Been ages since I did ActionScript, but isn't it prototype? I remember in AS3 you can not extend Math. – epascarello Nov 06 '17 at 16:56
  • No idea about actionscript, but if it's like JS: https://stackoverflow.com/questions/7694501/class-vs-static-method-in-javascript – jmargolisvt Nov 06 '17 at 16:57
  • @epascarello The OP is trying to add a static property (on the constructor)? Jezzamon: Do you mean you used to be able to do it in AS2, but can't in AS3? https://forums.adobe.com/thread/785932 This article says you used to be able to add properties to `Math` but that was disallowed in AS3 – Ruan Mendes Nov 06 '17 at 17:02
  • @JuanMendes I'm trying to do this in ActionScript 2. I'm working with an old project that doesn't compile at the moment, AFAIK it used to work (maybe with an older version of the flash authoring tool?) – Jezzamon Nov 07 '17 at 05:31
  • @jmargolisvt It is like JS, but the Math object is static. I was thinking something like this should work, but seems like it doesn't: https://stackoverflow.com/questions/27580890/extending-math-object-through-prototype-doesnt-work – Jezzamon Nov 07 '17 at 05:32

2 Answers2

1

To my mind looks impossible. Create static sinD method in separate class.

stesel
  • 37
  • 3
1

The 'problem' lies with ActionScript 2's static type checking. You can't directly modify a class because it checks that the property you're trying to access exists. However, you can do it if you bypass the type checking:

var Math2 = Math; // thing now holds a reference to the same Math class, but with no type set
// Add a new method
Math2.sinD = function(angle) {
    return Math.sin(angle*(Math.PI/180));
};
// Now the Math has 'sinD' as a method

Or alternatively... (these both do the same thing)

Math['sinD'] = function(angle) {
    return Math.sin(angle*(Math.PI/180));
};

However, this doesn't really help, because the static type checking is enforced at the calling places as well, so you can access any dynamically added methods.

Math.sinD(30) // This will not compile

Instead, you need to do:

var Math2 = Math;
Math2.sinD(30) // returns 0.5
Math['sinD'](30); // also returns 0.5

At which point, you may as well just create your own class rather than modifying the existing class.

Fortunately, for my case this means that there aren't any usages of these extensions (at least not statically typed usages), so I should be able to safely delete the extensions and not worry about it :)

Jezzamon
  • 1,453
  • 1
  • 15
  • 27