May 4, 2015

Notes on object-oriented JavaScript for o-o developers (part 2)

This post continues with more notes on distinctive features of object-oriented JavaScript as described in the book The Principles of Object-Oriented JavaScript.

The post is a follow-up to the earlier Part 1.

**  Regardless of how a function is defined and what its declared signature, it can be called with any number of parameters without triggering a runtime error.

Almost always, you do want to pass and to use the parameters as declared and as named. If for no other reason, do this for the sake of making the code better self-documenting.

Otherwise, within the context of each function there is a special array called arguments[] that contains the actual params for the call. You can use arguments[] to get a count of params and to access their values.

**  There is no function overloading.

If a function is defined more than once, it is the most recent definition that is used. The others are effectively overwritten.

**  There are special methods on functions.

Since functions are objects, it's possible that those objects have methods. There are at least three:  call(), apply(), and bind().

They are a bit too complicated to write about for these concise notes, so I won't describe them any further. I just wanted to mention that they exist and to reinforce the notion that functions are objects to which methods can be applied.

**  Objects can be made non-modifiable in different degrees.

(1) You can prevent properties from being added to an object by calling Object.preventExtensions() on it. In other respects, the object is still modifiable.

  var obj = new Object;


  obj.greeting = 'hello, world';  // Not allowed.

(2)  You can prevent properties from being added or removed from an object by calling Object.seal() on it. The values of the properties can be changed.

This makes the object similar to those created in a strongly-typed language with classes.

  var obj = new Object; = 'Turtle';


  obj.greeting = 'hello, world';  // Not allowed.
  delete;                // Not allowed. = 'Tortoise';          // Okay.

(3)  You can prevent properties from being added or removed, and also prevent the values of properties from being changed by calling Object.freeze() on it. In general, this is sometimes called an immutable object.

  var obj = new Object; = 'Turtle';


  obj.greeting = 'hello, world';  // Not allowed.
  delete;                // Not allowed. = 'Tortoise';          // Not allowed.

(Continued at Part 3.)

No comments:

Post a Comment