Javascript doesn't have support for muptiple inheritance.That means that objects by default can inherite only from one class (constructor). But because of expressive power of language, we can easily implement multiple inheritance with mixin pattern.
At the begining, let't quote Stoyan Stefanov from his book Javascript patterns:
Code reuse is the goal - inheritance is just one of options throughout we can achive code reuse
Lets see some code:
function mix() {// no parameters specified
var arg, prop, child = {};
for (arg = 0; arg < arguments.length; arg += 1) {// length
for (prop in arguments[arg]) {// browse properties
if (arguments[arg].hasOwnProperty(prop)) {// check if properties exists
child[prop] = arguments[arg][prop]; //copy
}
}
}
return child;
}
// call a function with mixed objects as arguments
var cake = mix(
{eggs: 2, large: true},
{butter: 1, salted: true},
{flour: "3 cups"},
{sugar: "sure!"}
);
As you can see, it is simple to copy properties with this pattern, and emulate multiple inheritance. One interesting thing in this pattern is that in function mix there are no paramaters, all the job is done with arguments. First we detect arguments length, then check if propeties exists and finally we copy them into new object. This example is also great because it uses nested loops and conditions.Happy Coding.
No comments:
Post a Comment