码迷,mamicode.com
首页 > Web开发 > 详细

js封装(常见)

时间:2017-09-10 18:45:06      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:func   fun   his   zha   prot   object   log   end   prototype   

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

 

巧妙

// 类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

闭包

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

 

js封装(常见)

标签:func   fun   his   zha   prot   object   log   end   prototype   

原文地址:http://www.cnblogs.com/alan-alan/p/7501626.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!