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());
    }
  • 相关阅读:
    修改eclipse的背景色(转载)
    c#调用 windows api实现WinForm中嵌入EXE程序
    VS2008序列号
    Microsoft Visual Studio 2005 获取与升级
    Oracle数组一般可以分为固定数组和可变数组
    深圳香港之行杂记
    [难过]小明住院了
    青岛之行杂记
    喀纳斯之行杂记
    亲历北京721大雨
  • 原文地址:https://www.cnblogs.com/sdgjytu/p/4200059.html
Copyright © 2011-2022 走看看