js封装(常见)
Posted alan-alan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
巧妙
// 类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封装(常见)的主要内容,如果未能解决你的问题,请参考以下文章
VSCode自定义代码片段14——Vue的axios网络请求封装