javascript模式——Mixin

Mixin是一种扩展收集功能的方式,能提高代码的复用率。

 

在javascript中,原型可以继承于其它对象的原型,并且可以为任意数量的实例定义属性。可以利用这一点来促进函数的复用。

 

下面一段代码就是将一些可以被复用的代码利用underscore.js里的_.extend对原型扩展,以实现高复用。

// 一些代码,可以被下面的类混入,

var controls = {

    moveForward: function(){

        console.log(this.name + ' move forward');

    },

    moveLeft: function(){

        console.log(this.name + ' move left');

    },

    moveRight: function(){

        console.log(this.name + ' move right');

    }

}



// Car类

function Car(){

    this.name = 'car';

    this.moveBackward = function(){

        console.log(this.name + ' move backward');

    }

}



// Airplane类

function Airplane(){

    this.name = 'airplane';

    this.moveUp = function(){

        console.log(this.name + ' move up');

    }

    this.moveDown = function(){

        console.log(this.name + ' move down');

    }

}

_.extend(Car.prototype, controls);

_.extend(Airplane.prototype, controls);



var car = new Car()

car.moveRight();



var airplane = new Airplane()

airplane.moveLeft();

 

除了使用underscore.js里的方法进行对象扩展,我们也可以自己实现混入功能,像一些有独特需求的,比如指定混入的方法名等等。

// 一些代码,可以被下面的类混入,

var controls = {

    moveForward: function(){

        console.log(this.name + ' move forward');

    },

    moveLeft: function(){

        console.log(this.name + ' move left');

    },

    moveRight: function(){

        console.log(this.name + ' move right');

    }

}



// Car类

function Car(){

    this.name = 'car';

    this.moveBackward = function(){

        console.log(this.name + ' move backward');

    }

}



function mixin( receivingClass, givingClass ) {

    // only provide certain methods

    if ( arguments[2] ) {

        for ( var i = 2, len = arguments.length; i < len; i++ ) {

            receivingClass[arguments[i]] = givingClass[arguments[i]];

        }

    }

}



mixin(Car.prototype, controls, 'moveForward');



var car = new Car();

car.moveForward() // car move forward 

car.moveLeft() //  error:undefined is not a function  

 

你可能感兴趣的:(JavaScript)