JS设计模式——1.富有表现力的JS

时间:2014-02-23 04:55:26   收藏:0   阅读:249

创建支持链式调用的类(构造函数+原型)

bubuko.com,布布扣
Function.prototype.method = function(name, fn){
    this.prototype[name] = fn;
    return this;
};

//构造函数+原型 创建类
var Anim = function(){};
Anim.method(‘starts‘, function(){
    console.log(‘starts‘);
}).method(‘ends‘, function(){
    console.log(‘ends‘);
});

var a = new Anim(); //注意new不能少
a.starts();
a.ends();
bubuko.com,布布扣

匿名函数创建闭包构造私有变量

bubuko.com,布布扣
var baz;
(function(){
    var foo = 10; //私有变量
    var bar = 2;
    baz = function(){ //访问私有变量的接口
        return foo * bar;
    };
})();
console.log(baz());
bubuko.com,布布扣

对象的易变性

这个没什么稀奇的,了解了原型链是怎么一回事,这个跟不不在话下。

bubuko.com,布布扣
var Person = function(name, age){
    this.name = name;
    this.age =age;
};

Person.method(‘getName‘, function(){
    return this.name;
}).method(‘getAge‘, function(){
    return this.age;
});
var alice = new Person(‘alice‘, 95);
var bill = new Person(‘bill‘, 30);

Person.method(‘getGreeting‘, function(){ //在创建实例后继续添加方法
    return ‘Hi ‘ + this.getName() + ‘!‘ ;
});

alice.displayGreeting = function(){
    return this.getGreeting();
};

console.log(alice.getGreeting());
console.log(bill.getGreeting());
console.log(alice.displayGreeting());
/*bill.displayGreeting();*/
bubuko.com,布布扣

原文:http://www.cnblogs.com/JChen666/p/3561072.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!