Prototype This page is part of the Prototype JavaScript framework documentation.
Overview | (...)

The Prototype Object.extend function amends an object with the properties of a second object, effectivly combining them.

Syntax


  Object.extend(objA, objB); // Amends objA with objB

The function also returns the changed objA for direct usage in an assignment or function call.

Properties in objB override properties of the same name in objA.

Examples

Basic usage:


  objA = {name: "Joe", age: "12"};
  objB = {name: "Tom"};
  Object.extend(objA, objB);
  alert(objA.name); // "Tom" 

Usage with assignment:


  objA = {name: "Joe", age: "12"};
  objC = Object.extend(objA, {name: "Tom"});
  objD = Object.extend(objA, {name: "Jim"});

  alert(objC.name); // "Tom" 
  alert(objD.name); // "Jim" 
  alert(objA.name); // "Jim", note that objA always gets changed

Usage in a function call:


  objA = {name: "Joe", age: "12"};
  alert(Object.extend(objA, {name: "Tom"}).name); // "Tom" 

Usage to create a shallow clone:


  objA = {name: "Joe", age: "12"};
  objC = Object.extend({}, objA);

“Shallow” in that properties in objA, which are objects themselves, do not get cloned as well.


  objA = {name: "Joe", age: "12", car:{make: "Honda"}};
  objC = Object.extend({}, objA);
  objC.car.make = "Toyota";
  alert(objA.car.make); // "Toyota" 

A common use for Object.extend() in script.aculo.us is to update default options with user-supplied overrides.