zoukankan      html  css  js  c++  java
  • javascript设计模式1

    普通写法

    function startAnimation(){
        ...
    }
    function stopAnimation(){
        ...
    }

    对象类

    /*Anim class*/
    var Anim=function(){
        ...
    };
    Anim.prototype.start = function() {
        ...
    };
    Anim.prototype.stop = function() {
        ...
    };
    /*Usage*/
    var myAnim=new Anim();
    myAnim.start();
    ...
    myAnim.stop();
    ...

    也可以这样写

    var Anim=function(){
        ...
    };
    Anim.prototype={
        start:function(){
            ...
        },
        stop:function(){
            ...
        }
    };

    再尝试一种

    Function.prototype.method=function(name,fn){
        this.prototype[name]=fn;
    };
    var Anim=function(){
        ...
    };
    Anim.method('start',function(){
        ...
    });
    Anim.method('stop',function(){
        ...
    });

    更进一步

    Function.prototype.method=function(name,fn){
        this.prototype[name]=fn;
        return this;
    };
    var Anim=function(){
        ...
    };
    Anim.method('start',function(){
        ...
    }).
    Anim.method('stop',function(){
        ...
    });

    利用匿名函数我们可以这样

    (function(){
        var foo=10;
        var bar=2;
        alert(foo*bar);
    })();

    也可以这样

    (function(foo,bar){
        alert(foo*bar);
    })(10,2);

    在js中,一切都是对象

    function displayError(message){
        displayError.numb++;
        alert(message);
    };
    displayError.numb=0;

    引申一下

    function Person(name,age){
        this.name=name;
        this.age=age;
    };
    Person.prototype={
        getName:function(){
            return this.name;
        },
        getAge:function(){
            return this.age;
        }
    }
    var alice=new Person('Alice',26);
    var bill=new Person('Bill',23);
    Person.prototype.getGreeting=function(){
        return 'Hi'+this.getName()+'!';
    };
    alice.displayGreeting=function(){
        alert(this.getGreeting());
    }
  • 相关阅读:
    boxShadow通用css效果
    electron安装+运行+打包成桌面应用+打包成安装文件+开机自启动
    electron-vue项目创建失败
    dpr——设备像素比(device pixel ratio)
    electron与vue集成
    一文让你理解vue history和hash模式实现
    vue router生命周期说明
    Vue keep-alive实践总结
    Vuejs路由过度动画
    ReactJS 的5种路由模式
  • 原文地址:https://www.cnblogs.com/sdgjytu/p/4200059.html
Copyright © 2011-2022 走看看