Reputation: 7050
In PHP, a class can implement the ArrayAccess interface, so the class can be instantiate and accessed like:
class MyClass implements ArrayAccess {
protected $data = array();
public function offsetGet($offset) {
return isset($this->data[$offset]) ? $data[$offset] : null;
}
public function offsetSet($offset, $value) {
$this->data[$offset] = $value;
}
public function __toString()
{
return print_r($this->data);
}
}
$a = new MyClass;
$a['item'] = 10;
$a['item2'] = 'adsf';
echo $a;
// Outputs Array( 'item' => 10, 'item2' => 'adsf' )
Is there anything like this in Javascript? I want to be able to create an iterator class in Javascript, but the items can be accessed by using the bracket notation instead of using get('item')
/set('item2', 'asdf')
so it can act like an Array instead of an Object, but still having all the functions from my constructor (next, prev, is, reset, etc)
I'm asking this because AngularJS, when using angular.element()
, it returns an object (?) like Object [div.id1]
in firebug console
Upvotes: 2
Views: 431
Reputation: 26706
The answer is yes, but not in any app that is intended to be used by the general public.
ECMAScript 5 supports 'get' and 'set' declarations (on known properties), and in future revisions will support proxies (which could listen for any changes to an object), but if your application is going to support IE anything, or any devices where users aren't opting into downloading developer browsers, and enabling dev-switches, you're going to have to either leave a lot of users behind for a few years (consider contract-lengths for smartphones, and that mobile browsers still aren't there), or implement the old version and test compatibility inside try-catch clauses, because using these features otherwise could cause hard exceptions, or just not work, depending.
And thus, yes, but you'll have to do it the old way, anyway.
Upvotes: 1