etlolap
etlolap

Reputation: 531

Javascript function, extend an object with an extension

This piece of code is from Addy Osmani's online book, "Learning JavaScript Design Patterns".

// Extend an object with an extension
function extend( extension, obj ){
  for ( var key in extension ){
    obj[key] = extension[key];
  }
}

It claims it can extend an object with an extension. It work well in the sample on the book. The controlCheckbox can function well for both definitions, Subject and DOM checkbox.

<input id="mainCheckbox" type="checkbox"/>
...
var controlCheckbox = document.getElementById( "mainCheckbox" ),
...
extend( new Subject(), controlCheckbox );
...
controlCheckbox["onclick"] = new Function( "controlCheckbox.Notify(controlCheckbox.checked)" );

But I just can't get the point why it is extended? The function definition of extend looks like overrding, instead of extending, controlCheckbox from an DOM checkbox to Subject, in my poor eyes. Can someone help me understand?

Upvotes: 2

Views: 633

Answers (2)

kol
kol

Reputation: 28688

Here is an example:

function extend( extension, obj ){
  for ( var key in extension ){
    obj[key] = extension[key];
  }
}

var obj = { a: 1, b: 2 },
    extension = { b: 20, c: 30 };

console.log("Before: ", obj);
extend(extension, obj);
console.log("After: ", obj);

Output:

Before:  Object {a: 1, b: 2} 
After:  Object {a: 1, b: 20, c: 30}

It's easy to see what's happened:

  1. Field a didn't exist in extension, so it remained unchanged.
  2. Field b existed in both objects, so it was overwritten by extension's field b.
  3. Field c existed only in extension, so it was added to obj.

Upvotes: 0

Joren
Joren

Reputation: 3297

What extend does is add all attributes from extension to obj and overwrite the ones already existing.

When you say obj['attr'] = 'foo' in javascript, you create the attribute attr in the object obj and assign foo to it. If attr already exists in obj, you will overwrite it with foo.

An alternative syntax would be obj.attr='foo', but this way, you can't use dynamic attribute names (variables, like in your example key is)

Some useful links:

Upvotes: 1

Related Questions