js 组件的写法

var Test1 = function(){

        var name = "";

        this.setName = function(username){

            name = username;

        }

        this.getName = function(){

            return name;

        }

        this.sayHello = function(){

            return "Hello " + this.getName();

        }

        return this;

    }();

    Test1.setName("penngo");

    console.log("Test1======" + Test1.getName());

    console.log("Test1======" + Test1.sayHello());



    // 第二种

    var Test2 = function(){

        var name = "";

        return {

            setName:function(username){

                name = username;

            },

            getName:function(){

                return name;

            },

            sayHello:function(){

                return "Hello " + this.getName();

            }

        };

    }();

    Test2.setName("penngo");

    console.log("Test2======" + Test2.getName());

        console.log("Test2======" + Test2.sayHello());

 

你可能感兴趣的:(js)