Traits.Js Robust Object Composition and High-Integrity Objects for Ecmascript 5

Traits.Js Robust Object Composition and High-Integrity Objects for Ecmascript 5

traits.js Robust Object Composition and High-integrity Objects for ECMAScript 5 Tom Van Cutsem Mark S. Miller Software Languages Lab Google, USA Vrije Universiteit Brussel, Belgium [email protected] [email protected] Abstract add class-like abstractions with mixin- or trait-like capabili- This paper introduces traits.js, a small, portable trait ties abound. What sets traits.js apart? composition library for Javascript. Traits are a more robust alternative to multiple inheritance and enable object com- Standard object representation format traits.js rep- position and reuse. traits.js is motivated by two goals: resents traits in terms of a new meta-level object de- first, it is an experiment in using and extending Javascript’s scription format, introduced in the latest ECMAScript recently added meta-level object description format. By 5th edition (ES5) [3]. The use of such a standard format, reusing this standard description format, traits.js can rather than inventing an ad hoc representation, allows be made more interoperable with similar libraries, and even higher interoperability with other libraries that use this with built-in primitives. Second, traits.js makes it con- format, including the built-in functions defined by ES5 venient to create “high-integrity” objects whose integrity itself. We briefly describe ES5’s new object-description cannot be violated by clients, an important property in the API in the following Section. We show how this standard context of interaction between mutually suspicious scripts. object description format lends itself well to extensions Categories and Subject Descriptors D.3.2 [Language of Javascript object semantics, while remaining interop- Classifications]: Object-oriented languages erable with other libraries. Support for high integrity traits.js facilitates the cre- General Terms Design, Languages ation of so-called “high-integrity” objects. By default, Keywords Traits, Javascript Javascript objects are extremely dynamic: clients can add, remove and assign to any property, and are even allowed to rebind the this pseudovariable in an object’s 1. Introduction methods to arbitrary other objects. While this flexibility We introduce traits.js, a small, standards-compliant trait is often an asset, in the context of cooperation between composition library for ECMAScript 5, the latest standard untrusted scripts it is a liability. ECMAScript 5 intro- of Javascript. Traits are a more robust alternative to classes duces a number of primitives that enable high-integrity with multiple inheritance. objects, yet not at all in a convenient manner. An ex- A common pattern in Javascript is to add (“mixin”) the plicit goal of traits.js is to make it as convenient to properties of one object to another object. traits.js pro- create high-integrity objects as it is to create Javascript’s vides a few simple functions for performing this pattern standard, dynamic objects. safely as it will detect, propagate and report conflicts (name Minimal traits.js introduces just the necessary features clashes) created during a composition. While such a library to create, combine and instantiate traits. It does not add is certainly useful, it is by no means novel. Because of the concept of a class to Javascript, but rather reuses Javascript’s flexible yet low-level object model, libraries that Javascript functions for the roles traditionally attributed to classes. Inspired by the first author’s earlier work [7], a class in this library is just a function that returns new trait instances. Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers or to redistribute Availability traits.js can be downloaded from www. to lists, requires prior specific permission and/or a fee. PLASTIC ’11 October 24th, Portland. traitsjs.org and runs in all major browsers. It also runs Copyright c 2011 ACM [to be supplied]. $10.00 in server-side Javascript environments, like node.js. 2. ECMAScript 5 descriptors. This object, which we will refer to as a property Before introducing traits.js proper, we briefly touch descriptor map, describes both the properties and the meta- upon a number of features introduced in the most recent ver- data (writability, enumerability, configurability) of the object sion of ECMAScript. Understanding these features is key to to be created. Armed with this knowledge, we could have understanding traits.js. also defined the point object explicitly as: Property Descriptors ECMAScript 5 defines a new object- var point = Object.create(Object.prototype, f manipulation API that provides more fine-grained control x: f value: 5, over the nature of object properties [3]. In Javascript, objects enumerable: true, are records of properties mapping names (strings) to values. writable: true, A simple two-dimensional point whose y-coordinate always configurable: true g, equals the x-coordinate can be defined as: y: f get: function () f return this .x; g, enumerable: true, var point = f configurable: true g, x: 5, toString: f value: function() f...g, get y() f return this .x; g, enumerable: true, toString: function() f return ’[Point ’+this .x +’]’; g writable: true, g; configurable: true g g); ECMAScript 5 distinguishes between two kinds of prop- erties. Here, x is a data property, mapping a name to a value Tamper-proof Objects ECMAScript 5 supports the cre- directly. y is an accessor property, mapping a name to a “get- ation of tamper-proof objects that can protect themselves ter” and/or a “setter” function. The expression point.y im- from modifications by client objects. Objects can be made plicitly calls the getter function. non-extensible, sealed or frozen. A non-extensible object ECMAScript 5 further associates with each property cannot be extended with new properties. A sealed object is a a set of attributes. Attributes are meta-data that describe non-extensible object whose own (non-inherited) properties whether the property is writable (can be assigned to), enu- are all non-configurable. Finally, a frozen object is a sealed merable (whether it appears in for-in loops) or config- object whose own properties are all non-writable. The call urable (whether the property can be deleted and whether Object.freeze(obj) freezes the object obj. As we will its attributes can be modified). The following code snippet describe in Section 6, traits.js supports the creation of shows how these attributes can be inspected and defined: such tamper-proof objects. var pd = Object.getOwnPropertyDescriptor(o,’x’); Bind A common pitfall in Javascript relates to the peculiar // pd = f binding rules for the this pseudovariable in methods [2]. // value: 5, For example: // writable : true , // enumerable: true , var obj = f // configurable : true x:1, // g m: function () f return this .x; g Object.defineProperty(o,’z’, f g; get: function () f return this .x; g, var meth = obj.m; // grab the method as a function enumerable: false, meth(); // ”this” is now set to the global object configurable: true g); Javascript methods are simply functions stored in objects. When calling a method obj.m(), the method’s this pseu- The pd object and the third argument to defineProperty dovariable is bound to obj, as expected. However, when ac- are called property descriptors. These are objects that de- cessing a method as a property obj.m and storing it in a scribe properties of objects. Data property descriptors de- variable meth, as is done in the above example, the func- clare a value and a writable property, while accessor tion loses track of its this-binding. When it is subsequently property descriptors declare a get and/or a set property. called as meth(), this is bound to the global object by de- The Object.create function can be used to generate fault, returning the wrong value for this.x. new objects based on a set of property descriptors directly. There are other ways for the value of this to be rebound. Its first argument specifies the prototype of the object to Any object can call a method with an explicit binding for be created (every Javascript object forwards requests for this, by invoking meth.call(obj). While that solves the properties it does not know to its prototype). Its second problem in this case, unfortunately, in general, malicious argument is an object mapping property names to property clients can use the call primitive to confuse the original method by binding its this pseudovariable to a totally unre- unlike mixin-based or multiple inheritance, trait composi- lated object. To guard against such this-rebinding, whether tion is commutative and associative. This tremendously re- by accident or by intent, one can use the ECMAScript 5 duces the cognitive burden of reasoning about deeply nested bind method, as follows: levels of trait composition. In languages that support traits as a compile-time entity (similar to classes), trait composi- obj.m = obj.m.bind(obj); // fixes m’s ”this” to ”obj” tion can be entirely performed at compile-time, effectively var meth = obj.m; “flattening” the composition and eliminating any composi- meth(); // returns 1 as expected tion overhead at runtime. Since their publication in 2003, traits have received Now m can be selected from the object and passed around widespread adoption in the PL community, although the de- as a function, without fear of accidentally having its this tails of the many traits implementations differ significantly rebound to the global object, or any other random object. from the original implementation defined for Smalltalk. 3. Traits Traits have been adopted in a.o. Perl, Fortress and Scheme [4]. Traits were originally defined as “composable units of be- 4.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    8 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us