JavaScript: The Definitive Guide

Previous Chapter 21
JavaScript Reference
Next
 

Object.assign() Method

Name

Object.assign() Method---overload the assignment operator

Availability

Navigator 3.0

Synopsis

object.assign(value)

Arguments

value

The value to be assigned. The assign() method should, in some fashion, assign value to the object.

Returns

Nothing.

Description

The assign() method is not one you usually call explicitly in your JavaScript code. Instead you define this method for certain objects, and the system invokes the method automatically when a value is assigned to that object.

If an object o has an assign() method defined, then the assignment:

o = value;
is translated to the following function call:

o.assign(value);

The assign() method should be written to expect a single argument, which will always be the value of the right-hand side of an assignment operator. When invoked, the object will refer to the left-hand side of the assignment. The body of the method should "assign," in some appropriate fashion, the value to the object.

Usage

You might define the assign() method when you want assignment to an object to perform some sort of side effect. For example, in client-side JavaScript, assigning a URL value to the location field of a window object causes the browser to load that URL into the window.

Sometimes, you may want to define an assign() method for only one single special object. In other cases, however, you will want all instances of a class of objects to have a special assignment behavior. In this case, you should set the assign() method in a constructor function or a prototype object.

Example

The following code shows how you could define an assign() method for a class of objects so that when one object of this class is assigned to another, the object's fields will be assigned "by value," rather than assigning "by reference."

// Define a function suitable for use as our assign() method.
function copy_fields(value) 
{
    for (field in value) this[field] = value[field];
}
// Define it as the assign() method in a prototype object, so that
// all instances of the object type have this assign() method.
MyObject.prototype.assign = copy_fields;

See Also

"Object"


Previous Home Next
Object Book Index Object.constructor

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell
Hosted by uCoz