别动手动脚的,把手拿开!
我是在地球上成长的赛亚人!

Posted by 小程同学| Blog on March 24, 2018

几种方式都是大同小异

  1. 首先,如果想要封装,就必须要用到函数,闭包
  2. 用到闭包,就必须暴露出一个属性给window对象

创建js类

方式一: (function(window,document){ var Student=function(options){ this.name=options.name; this.age=options.age; } Studentprototype={ constructor:Person, run:function(){ console.log(‘hello’) } } window.student=function(obj){ return new Studentobj) } })(window,document) //调用 student({ name:’小明’, age:20 })

方式二: var person=(function(window,document){ var Student=function(options){ this.name=options.name; this.age=options.age; } Studentprototype={ constructor:Person, run:function(){ console.log(‘hello’) } } return { student:function(obj){ new Student(obj) } } })(window,document) //调用 person.student({ name:’小明’, age:20 })

方式三:比较新奇 !function (window) { function Student(options) { return new Student.prototype.init(options); } Student.prototype = { init: function (options) { return this.name = options.name, this.age = options.age, this.run(); }, run: function () { console.log(this.name + ‘,跑起来了…’); } }; Student.prototype.init.prototype = Student.prototype; window.student = Student; }(window); //调用 var person = student({ name: ‘小明’, age: 20 }); console.log(person);