當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
javascript模式——Mixin
生活随笔
收集整理的這篇文章主要介紹了
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 methodsif ( 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
總結
以上是生活随笔為你收集整理的javascript模式——Mixin的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: angularJs跨域
- 下一篇: UVa 11762 (期望 DP) Ra