浓缩解读前端系列书籍一周一章前端书

一周一章前端书·第11周:《你不知道的JavaScript(上)

2018-01-07  本文已影响17人  梁同学de自言自语

第6章: 行为委托

6.1 面向委托的设计

6.1.1 类理论
class Transport {
    //构造函数
    Transport(id,passengerNum,name);  
    
    id;
    passengerNum;   //乘客数
    name;         //品牌名字
    //启动
    launch(){
        console.log('载重人数:'+passengerNum,'品牌名字:'+name);
    };    
}

class Car inherits Transport{
    //构造函数
    Car(id,passengerNum,name,wheelNum){
        super(id,passengerNum,name);
        wheelNum = wheelNum;    
    }
    
    wheelNum;  //轮子数量
    launch(){
        super();
        console.log('轮子数量:' + wheelNum);
    };   
}

class Aircraft inherits Transport{
    //构造函数
    Aircraft(id,passengerNum,name,wingNum){
        super(id,passengerNum,name);
        wingNum = wingNum;
    }
    
    wingNum;    //机翼数量
    launch(){
        super();
        console.log('机翼数量:' + wingNum);
    }
}
6.1.2 委托理论
class Transport {
    setId : function(id){
        this.id = id;
    },
    setPassengerNum : function(num){
        this.passengerNum = num;
    },
    setName : function(name){
        this.name = name;
    },
    launch(){
        console.log('载重人数:'+this.passengerNum,'品牌名字:'+this.name);
    },    
}

//Car委托Transport
Car = Object.create(Transport);
Car.prepareTransport = function(id,passengerNum,name,wheelNum){
    this.setId(id);
    this.setPassengerNum(passengerNum);
    this.wheelNum = wheelNum;
}
Car.prepareLaunch = function(){
    this.launch();
    console.log('轮子数量:' + wheelNum);
}
“面向类”和“面向委托”设计模式的区别

注意:在两个或两个以上互相委托的对象之间,创建循环委托是禁止的。

6.1.3 比较思维模型
/**
 * 交通工具
 * @param {*} id 
 */
function Transport(id,name,passengerNum){
    this.id = id;
    this.name = name;
    this.passengerNum = passengerNum;
}
Transport.prototype.launch = function(){
    console.log('载重人数:'+this.passengerNum,'品牌名字:'+this.name);
}


/**
 * 汽车
 * @param {*} id 
 * @param {*} name 
 * @param {*} passengerNum 
 */
function Car(id,name,passengerNum){
    Transport.call(this,id,name,passengerNum);
}
Car.prototype = Object.create(Transport.prototype);
Car.prototype.run = function(){
    this.launch();
}

//实例化
var lexus = new Car(1,'雷克萨斯',8);
var bmw = new Car(2,'宝马',8);

lexus.run();
bmw.run();
/**
 * 交通工具
 */
Transport = {
    init : function(id,name,passengerNum){
        this.id = id;
        this.name = name;
        this.passengerNum = passengerNum;
    },
    launch : function(){
        console.log('载重人数:'+this.passengerNum,'品牌名字:'+this.name);
    }
}

/**
 * 汽车
 */
Car = Object.create(Transport);
Car.run = function(){
    this.launch();
}


//实例化
var mazda = Object(Car);
mazda.init(1,'马自达',4);
mazda.run();

var toyota = Object(Car);
toyota.init(2,'丰田',4);
toyota.run();

6.2 类与对象

/**
 * Widget父类
 * @param {*} width 
 * @param {*} height 
 */
function Widget(width,height){
    this.width = width;
    this.height = height;
    this.$elem = null;
}
Widget.prototype.render = function($where){
    if(this.$elem){
        this.$elem.css({
            width : this.width + 'px',
            height: this.height + 'px'
        }).appendTo($where);
    }
}


/**
 * Button子类
 * @param {*} width 
 * @param {*} height 
 * @param {*} label 
 */
function Button(width,height,label){
    Widget.call(this,width,height);
    this.label = label;
}
Button.prototype = Object.create(Widget.prototype);
//重写render方法
Button.prototype.render = function($where){
    //super调用
    Widget.prototype.render.call(this,$where);
    //绑定事件
    this.$elem.click(this.onClick.bind(this));
}
Button.prototype.onClick = function(evt){
    console.log('Button'+this.label+' clicked!');
}


//调用
$(document).render(function(){
    var $body = $(document.body);

    var saveBtn = new Button(125,30,'暂存');
    var submitBtn = new Button(125,30,'提交');

    saveBtn.render($body);
    submitBtn.render($body);
})
/**
 * Widget父类
 */
var Widget = {
    init: function (width, height) {
        this.width = width || 50;
        this.height = height || 50;
        this.$elem = null;
    },
    insert: function ($where) {
        if (this.$elem) {
            this.$elem.css({
                width: this.width + 'px',
                height: this.height + 'px'
            }).appendTo($where);
        }
    }
}

/**
 * Button子类
 */
var Button = Object.create(Widget);
Button.setup = function(width,height,label){
    this.init(width,height);
    this.label = label || 'Default';
    this.$elem = $('<button>').text(this.label);
}
Button.build = function($where){
    this.insert($where);
    this.$elem.click(this.onClick.bind(this));
}
Button.onClick = function(evt){
    console.log('Button'+this.label+' clicked!');
}

//调用
$(document).render(function(){
    var $body = $(document.body);

    var saveBtn = Object.create(Button);
    saveBtn.setup(125,30,'暂存');

    var submitBtn = Object.create(Button);
    submitBtn.setup(125,30,'提交');

    saveBtn.build($body);
    submitBtn.build($body);
})

注意:

  • 在面向委托的代码中,没有像类一样,定义相同的方法名render(),而是定义了两个更具描述性的方法名insert()build(),在很多情况下,将构造和初始化步骤分开,更灵活;
  • 同时在面向委托的代码中,我们避免丑陋的显式伪多态调用Widget.callWidget.prototype.render.call,取而代之简单的相对委托调用this.init()this.insert()

6.3 更简洁的设计

/**
 * 父类Controller
 */
function Controller(){
    this.errors = [];
}
Controller.prototype.showDialog = function(title,msg){
    //...
}
Controller.prototype.success = function(msg){
    this.showDialog('Success',msg);
}
Controller.prototype.failure = function(err){
    this.errors.push(err);
    this.showDialog('Error',err);
}


/**
 * 登陆表单Controller子类
 */
function LoginController(){
    Controller.call(this);
}
//继承Controller
LoginController.prototype = Object.create(Controller.prototype);
//获取用户名
LoginController.prototype.getUser = function(){
    return docuemnt.getElmementById('username').value;
}
//获取密码
LoginController.prototype.getPwd = function(){
    return docuemnt.getElmementById('userPwd').value;
}
//表单校验
LoginController.prototype.validate = function(user,pwd){
    user = user || this.getUser();
    pwd = pwd || this.getPwd();

    if(!(user && pwd)){
        return this.failure('请输入用户名/密码!');
    }
    else if(pwd.length < 5){
        return this.failure('密码长度不能少于五位!');
    }

    return true;
}
//重写failure
LoginController.prototype.failure = function(err){
    Controller.prototype.failure.call(this,'登陆失败:'+err);
}


/**
 * 授权检查Controller子类
 * @param {*} login 
 */
function AuthController(login){
    Controller.call(this);
    this.login = login;
}
//继承Controller
AuthController.prototype = Object.create(Controller.prototype);
//授权检查
AuthController.prototype.checkAuth = function(){
    var user = this.login.getUser();
    var pwd = this.login.getPwd();

    if(this.login.validate(user,pwd)){
        this.send('/check-auth',{
            user : user,
            pwd : pwd
        })
        .then(this.success.bind(this))
        .fail(this.failure.bind(this));
    }
}
//发送请求
AuthController.prototype.send = functioin(url,data){
    return $.ajax({
        url : url,
        data : data
    })
}
//重写基础的success
AuthController.prototype.success = function(){
    Controller.prototype.success.call(this,'授权检查成功!');
}
//重写基础的failure
AuthController.prototype.failure = function(err){
    Controller.prototype.failure.call(this,'授权检查失败:'+err);
}


/**
 * 调用
 */
//除了继承,还要合成
var auth = new AuthController(new LoginController());
auth.checkAuth();
/**
 * Login
 */
var LoginController = {
    errors : [],
    getUser : function(){
        return docuemnt.getElmementById('username').value;
    },
    getPwd : function(){
        return docuemnt.getElmementById('userPwd').value;
    },
    validate : function(user,pwd){
        user = user || this.getUser();
        pwd = pwd || this.getPwd();

        if(!(user && pwd)){
            return this.failure('请输入用户名/密码!');
        }
        else if(pwd.length < 5){
            return this.failure('密码长度不能少于五位!');
        }

        return true;
    },
    showDialog : function(title,msg){
        //...
    },
    failure : function(err){
        this.errors.push(err);
        this.showDialog('Error','登陆失败:'+err);
    }
}


/**
 * Auth
 */
var AuthController = Object.create(LoginController);
AuthController.errors = [];
AuthController.checkAuth = function(){
    var user = this.login.getUser();
    var pwd = this.login.getPwd();

    if(this.login.validate(user,pwd)){
        this.send('/check-auth',{
            user : user,
            pwd : pwd
        })
        .then(this.success.bind(this))
        .fail(this.failure.bind(this));
    }
}
AuthController.send = functioin(url,data){
    return $.ajax({
        url : url,
        data : data
    })
}
AuthController.accepted = function(){
    this.showDialog('系统提示','授权检查成功!');
}
AuthController.rejected = function(err){
    this.showDialog('系统提示','授权检查失败:'+err)
}


/**
 * 调用
 */
var loginCtrl = Object.create(LoginController);
var authCtrl = Object.create(AuthController);

6.4 更好的语法

var LoginController = {
    errors : [],
    getUser() {
        //可以不用function来定义
    },
    getPwd() {
        //...
    }
}

var AuthController = {
    errors : [],
    checkAuth(){
        //...
    },
    send(){
        //...
    }
}

//把AuthController关联到LoginController
Object.setPrototypeOf(AuthController,LoginController);

6.5 内省

//类
function Fruit(){}
Fruit.prototype.something = function(){}
//实例
var fruit = new Fruit();
//判断实例的类型,以便调用某个方法
if(fruit instanceof Fruit){
    fruit.something();
}
//水果
function Fruit(){}
Fruit.prototype.something = function(){}
//苹果
function Apple(){}
Apple.prototype = Object.create(Fruit.prototype);
//苹果实例
var apple = new Apple();

//检测结果均为true
console.log(Apple.prototype instanceof Fruit);
console.log(Object.getPrototypeOf(Apple.prototype) === Fruit.prototype);
console.log(Fruit.prototype.isPrototypeOf(Apple.prototype));

console.log(apple instanceof Apple);
console.log(apple instanceof Fruit);

console.log(Object.getPrototypeOf(apple) === Apple.prototype);
console.log(Apple.prototype.isPrototypeOf(apple));
console.log(Fruit.prototype.isPrototypeOf(apple));

//或者通过鸭子类型的方式来检查,只要方法存在即调用
if(apple.something){
    apple.something();
}
var Fruit = {
    something : function(){}
};
var Apple = Object.create(Fruit);
var apple = Object.craate(Apple);

//检测结果均为true
console.log(Fruit.isPrototypeOf(Apple));
console.log(Object.getPrototypeOf(Apple) === Apple);

console.log(Fruit.isPrototypeOf(apple));
console.log(Apple.isPrototypeOf(apple));
console.log(Object.getPrototypeOf(apple) === Apple);

6.6 小结

上一篇下一篇

猜你喜欢

热点阅读