这2段有关javascript函数化模式【模块化模式】的总结,还需要好好地琢磨!!!

时间:2014-11-03 18:59:33   收藏:0   阅读:189

<script>
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
}
};
Object.method(‘superior‘, function (name) {
var that = this,
method = that[name];
return function ( ) {
return method.apply(that, arguments);
};
});
var mammal = function (spec) {
var that = {};
that.get_name = function ( ) {
return spec.name;
};
that.says = function ( ) {
return spec.saying || ‘‘;
};
return that;
};
//var myMammal = mammal({name: ‘Herb‘});
var cat = function (spec) {
spec.saying = spec.saying || ‘meow‘;
var that = mammal(spec);
that.purr = function (n) {
var i, s = ‘‘;
for (i = 0; i < n; i += 1) {
if (s) {
s += ‘-‘;
}
s += ‘r‘;
}
return s;
};
that.get_name = function ( ) {
return that.says( ) + ‘ ‘ + spec.name +
‘ ‘ + that.says( );
}
return that;
};
var myCat = cat({name: ‘Henrietta‘});
var coolcat = function (spec) {
var that = cat(spec),
super_get_name = that.superior(‘get_name‘);
that.get_name = function (n) {
return ‘like ‘ + super_get_name( ) + ‘ baby‘;
};
return that;
};

var myCoolCat = coolcat({name: ‘Bix‘});
var name = myCoolCat.get_name( );
// ‘like meow Bix meow baby‘

</script>
<script>
function createCar(numberOfDoors){
var numberOfWheels = 4;
function describe(){
return "I have " + numberOfWheels + " wheels and " + numberOfDoors + " doors.";
}
return {
describe: describe
};
}
function createOdometer(){
var mileage = 0;
function increment(numberOfMiles){ mileage += numberOfMiles;}
function report(){ return mileage; }
return {
increment: increment,
report: report
}
}

function createCarWithOdometer(numberOfDoors){
var odometer = createOdometer();
var car = createCar(numberOfDoors);
car.drive = function(numberOfMiles){
odometer.increment(numberOfMiles);
}
car.mileage = function(){
return "car has driven " + odometer.report() + " miles";
}
return car;
}


var twoFn=createCarWithOdometer(100);


console.log(twoFn);

 

</script>

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!