js封裝(常見)

var Person ={

    name :'alan',
    sayHello:function(){
        alert('hello '+ this.name);
    }

};

var p = Object.create(Person);
console.log(p);
p.sayHello();

 

 

 

js封裝(常見)閉包

function Person (info){
    this._init_(info);
}

Person.prototype ={
    constructor:Person,

    _init_:function(info){

        this.names = info.name;
        this.age = info.age;
        this.gender = info.gender;


    },
    sayHello:function(){
        // console.log('hello');
        alert('hello');
    }
    // demo:function(){},

};

var clzhang = new Person({
    name:'clzhang',
    age:'1111',
    gender:''
});

clzhang.sayHello()//hello

 

巧妙this

// 類jQuery 封裝
var Person = function (info){

    return new Person.prototype.init(info);
};

Person.prototype ={
    constructor:Person,

    init:function(info){

        this.names = info.name;
        this.age = info.age;
        this.gender = info.gender;


    },
    sayHello:function(){
        // console.log('hello');
        alert('hello2');
    }
    // demo:function(){},

};

Person.prototype.init.prototype = Person.prototype;

var clzhang = new Person({
    name:'clzhang',
    age:'1111',
    gender:''
});

clzhang.sayHello()//hello2

閉包spa

var Person = (function(window){


    var Person = function (info){

    return new Person.prototype.init(info);
};

Person.prototype ={
    constructor:Person,

    init:function(info){

        this.names = info.name;
        this.age = info.age;
        this.gender = info.gender;


    },
    sayHello:function(){
        // console.log('hello');
        alert('hello3');
    }
    // demo:function(){},

};

Person.prototype.init.prototype = Person.prototype;

return Person;
})();

var clzhang =  Person({
    name:'clzhang',
    age:'1111',
    gender:''
});

clzhang.sayHello()//hello3
相關文章
相關標籤/搜索