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

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

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();

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

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

对象的易变性

这个没什么稀奇的,了解了原型链是怎么一回事,这个跟不不在话下。(我们可以在创建实例后添加方法和修改方法,甚至删除方法)。

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();*/