Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Testing Prototypal Inheritance vs. Functional Composition" />
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  
</body>
</html>
 
//#Testing Prototypal Inheritance vs. Functional Composition
//Create an original object
var original = {
  name: "Darth",
  values: [1, 2, 3]
};
//Create a new object from it using Object.create
var newObject = Object.create(original);
//Give it a new property that matches a property on the prototype:
newObject.name = "Luke";
//Test if it works:
console.log(newObject.name);
console.log(original.name);
//Yes, it works as you would think. This is what it displays:
//"Luke"
//"Darth"
//That's because we created a `name` the property on the `newObject` that is 
//masking the `name` property on the `original`.
//But what happens if the `newObject` *doesn't have* a property that masks
//a property on the prototype?
//Add a number to the `values` array in the `newObject`:
newObject.values.push(4);
//Now check to see what happened to the `original.values` array:
console.log(original.values);
//Here's what it displays:
//[1, 2, 3, 4]
//Did you expect that?
//That happened because the `newObject` doesn't have its own array called `values`.
//So it's just using the `values` array on the prototype. You'll see the same
//effect for nested objects.
//Whether this is good or bad, it's is just how prototypal inheritance works.
//You can solve this by giving `newOobject` it's own `values` array, like this:
newObject.values = [];
//Now push a value into it:
newObject.values.push(10);
//Let's see how this affects the `newObject` and the `original`:
console.log(newObject.values);
console.log(original.values);
//Here's what it displays:
//[10]
//[1, 2, 3, 4]
//This now works because both objects now have their own arrays called `values`.
//This effect of prototypal inheritance causes a lot of confusion and, if
//you're not aware of it, can result in bugs that are very
//difficult to diagnose.
//If you want to make sure that properteries on objects belong to those objects, and not the prototype, don't use prototypeal inheritance to make new objects. Instead, use *functional composition*. Here's how:
//1. Create a function that returns an object with some default properties.
function template() {
  o = {
    name: "Darth",
    values: [1, 2, 3]
  };
  return o;
}
//2. Use the function to create a new object.
var anotherObject = template();
//3. Now check to see what this new object's properties are:
console.log(Object.keys(anotherObject));
//This displays:
//["name", "values"]
//All the of the new object's properties are it's own. There's now no danger that //the new object is referencing a property on a prototype. 
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
kittykatattackpro
0viewers