How would Object.defineProperty be in AS3?

2019-07-23 13:55发布

I'm an architect from a strong JavaScript background, but I did some .NET and Java in the past.

However, I wanted to put a hand on ActionScript3, which I was promised that is very related to JavaScript.

As a startup project I took on myself to try port to ActionScript3 one of my favorite assertion utils - should.js - that makes your test codes really pleasant to read.

Updated: 2013-02-19

I saw I confuse with my abstract speaking, so I replaced some of the post with the concrete question in mind. Here's the full picture:

Consider the following JavaScript code:

Object.defineProperty(Object.prototype, 'should'
, { set: function(){}
  , get: 
    function(){
       return new Assertion(Object(this).valueOf());
    }
  , configurable: true
  , enumerable  : false
  }
);

That is part of the implementation of the JavaScript module Should. The other part is a definition of a the class Assertion, that is constructed with a value, and implements a wide and nice set of assertion methods, against that value. Methods like like

var o = Assertion(actualValue)
o.equals(expectedValue1)
o.moreThan(expectedValue2)
o.contains(expectedValue3)

and aliases to keep english grammer

var o = Assertion(actualValue)
o.equal(expectedValue1)
o.contain(expectedValue3)

and aliases for the lazy sharpshooters, like

o.eql(expectedValue)
o.gt(expectedValue) //greater then
o.gte(...) //greater then or equal
//and so on... 

and some connectors that just return this, (which is the instance of Assertion constructed with the test value) like

o.be
o.and

What does it give you?

A test code that looks like this:

var person = getPerson();
Should.exist(person); //that's a static call, and that's easy

//but these are a member calls:
person.should.have("name","age","address","friends");  
person.name.should.equal("John");
person.age
  .should
      .be.number()
  .and.be.between(20,30);

person.address
  .should
    .be.string().and
    .startWith("\d").and
    .endWith(" st.")
  //or even
    .and.match(/^[0-9]{1,9}\s+[A-Z][a-z0-9 ]* st\.$/);

person.friends
  .should
    .be.array().and
    .be.between(3,5).and
    .containOnlyType(String);

Isn't that wonderful? it's plain English!

You could argue about aesthetics of indentation, where to put the and, and if they are at all necessary, but besides that - anybody can read or write it: Once you took the 'should' attribute that exists on every object but does not spoil map iterations - you can go on chaining whatever you have to claim regarding the value you started from.

It could have more nifty iteration tools, reflection utilities, be augmented with test functions relevant for your object model, and so on and so forth, but lets just get over the first step :)

But for that, you need every object in the system to feature a non-enumerable smart property called should that in it's getter function returns an Assertion object constructed with the this as the tested value.

(you ain't seen nothing yet - wait to see the beautiful rejection messages it gives! Yummie!! So yea - I would happily sacrifice the option to call an attribute "should"... and will happily give up intelisense as well - at least as long as it's plain English)

So, in comments, bfavaretto gave us the first step - we know how to prevent enumeration of an attribute - great & thanks!!

Now, can we make it a getter-attribute who's function can access the this?

When I'm done I'm going to put it in some public repo licensed under MIT, for all of us to have fun with :)

Help anybody?

3条回答
闹够了就滚
2楼-- · 2019-07-23 14:31

I confess I'm not keenly familiar with how Javascript works, but if I'm understanding defineProperties purpose correctly, it is a runtime dictation of not just what a property should be, but also the associated namespace to which it belongs (or at least what AS3 considers a namespace).

Class properties are either predefined & only modifiable via custom get() set() functions, or dynamic. Once compiled, their namespace cannot be changed (to my knowledge), so any non-private property is implicitly enumerable, and modifiable whether or not you've written getter/setters (ie: foo.a = value). According to Adobe...

Properties that you create are enumerable, but built-in properties are generally not enumerable.

That said, you can get a complete list of properties from a class by using describeType. Quite an exhaustive amount of info can be gleaned this way, and I suspect should suit your needs if you wanted to port Mozilla's recreated defineProperties example. Below is an example printing out only property values.

function showProps(obj:*):void {
    var desc:XML= describeType(obj);

    // public vars
    for each (var n:XML in desc.variable){
        trace(n.@name + ": " + obj[n.@name]);
    }
    // getters
    for each (n in desc.accessor){
        try {
            trace(n.@name + ": " + obj[n.@name]);
        } catch (error:Error) {
            trace("Unable to read write-only property.");
        }
    }
}

I hope this helps, but I'm certain I don't fully understand what you're trying to accomplish. If you could elaborate, that'd be appreciated.

查看更多
对你真心纯属浪费
3楼-- · 2019-07-23 14:35

You example is actually 90% correct - but define it like actionscript, not like javascript!

You can still define prototypes in AS3 and they will still work just like prototypes in AS2. The only difference in AS3 is the compiler. AVM2 for some reason does not cast prototypes to native classes (although I didn't test custom classes).

The Prototype Trick: Cast the class as an object.

Eg: if you create:

Array.prototype.random = function():void{}

Then create the object:

var myProtoArray:Array = new Array;

2 things will happen:

myProtoArray.random() //ERROR - this will fail, AVM2 did not map the prototype to Array

but

Object(myProtoArray).random() //WORKS

random() was cast to the Object class, then mapped to Array - I have no idea why!

Hope this helps, cheers.

查看更多
We Are One
4楼-- · 2019-07-23 14:51

Ok, guys, thanks for all the help, 22+ I'll give a summary for the people that are interested in the original question, and after that - I'll show you the outcome of my efforts.

The challange was made of two parts:

1 - prevent the augmented (=added on runtime) property from being enumerated

To the first part - thanks to @bfavaretto, commented on the question level - Object.setPropertyIsEnumerable - did the trick great.

2 - make the augmented property operate a getter function with access to the this so it can use it on the constructor of the returned value.

About this second part - Basically - I could not find a way to augment (=add) a property getter to a prototype, and have it operate on instances that enjoy it's API through the inheritance tree.

Anyway, within these limits - here's the outcome:

https://github.com/osher/should.as

Not exact porting because of the platform differences, and I still have some methods to catch up with the original should.js (like the HTTP testing methods) but close enough. The main difference is that instead

var o:Object = 
    { name : "Radagast"
    , color: "Brown"
    }
o.should.have.properties("name","color")
    .and.have.property("name","Radagast");
o.name.should.not.equal("Palandoo");
o.color.should.equal("Brown");

you have to go

o.should().have.properties("name","color")
       and.have.property("name","Radagast");
o.name.should().not.equal("Palandoo");
o.color.should().equal("Brown");

(the brackets - no getter possible - so the should attribute is a method, and you have to invoke it yourself)

Now if you get stuck and need help from the intellisense, you have to do this:

var should:tdd.Should = o.color.should();
should. <ctrl+space>

which kind'a takes the sting out, but for a peek in the intelisense - it helps

Important

One more thing - you have to force the static constructor of Should as soon in execution as you can, for example, I do it here:

[Suite]
[RunWith("org.flexunit.runners.Suite")]
public class my_awsome_test_suite
{
            //forces the static constructor of tdd.Should
    import tdd.Should;
    private static var s:Should = new Should(); 

    public var c1:testCase1;
    public var c2:testCase2;
    public var c3:testCase3;
    public var c4:testCase4;
    }

I'll probably add some propper README.md later, and more awsome member functions to tdd.Should

Have fun

查看更多
登录 后发表回答