2

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?

2 Answers 2

1

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:

Sign up to request clarification or add additional context in comments.

3 Comments

The explanation is okay, but that link is anything but "official".
@bfavaretto better now? ;)
Yes, thanks! Don't get me wrong, but w3schools' content quality is questionable, and, despite the name, it's not affiliated with the w3c. MDN (a wiki) is a better reference.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.