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  

 

转载于:https://www.cnblogs.com/winderby/p/4325087.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值