构造函数相信你们都不会陌生
在JS里,咱们对构造函数使用new
来新增实例闭包
1.将属性绑定到this
上
2.将方法绑定到prototype
上
3.使用new
来新增实例【建立不一样的引用类型】函数
function People() { this.name = '人' } People.prototype.walk = function () { console.log('walk') } let xiaoming = new People()
顾名思义,工厂模式就是像是工厂同样流水线般生产处一个个对象this
1.return
一个对象
2.建立不一样的引用类型prototype
function createPerson() { // 定义工厂 let person = { name: '人', walk: function () { console.log('walk') } } return person // 返回一个对象 } let xiaoming = createPerson() // 工厂生产对象
1.产生一个类的惟一实例
2.好处就是节约内存code
function createPeople() { let name return function (userName) { return name || (name = userName) } } let single = createPeople() console.log(single('人')) // '人' // 无论再传递任何值,也只会返回 '人' console.log(single('马')) // '马'
1.在JS中,通常咱们实现继承的过程就是混合模式
2.其概念就是提供可以被一个或者一组子类简单继承功能的类对象
function People(name, age) { this.name = name this.age = age } People.prototype.sayName = function () { console.log(this.name) } function Student(name, age, score) { People.call(this, name, age) this.score = score } function create(prototypeObj) { let empty = function () {} empty.prototype = prototypeObj return new empty() // return值以下 // { // __proto__:prototypeObj // } } Student.prototype = create(People.prototype) Student.prototype.work = function () { console.log('work') }
在js中,经常使用闭包的形式来实现继承
let Person = (function () { let name = '小明' function sayName() { console.log(name) } return { name: name, sayName: sayName } })()
好比我【订阅者】如今订阅了一个公众号,公众号【发布者】向我发布消息事件
实现一个jQuery的发布订阅案例内存
// 订阅者 $('div').on('click',function () {}) // 发布者 $('header').on('click',function () { $('div').trigger('click') })
代码io
let EventCenter = (function () { let events = {} function on(evt, handler) { // 实现监听效果 // 使用'或'是为了能够对同一个事件屡次进行回调 events[evt] = events[evt] || [] events[evt].push({ handler: handler }) } function fire(evt, args) { if (!events[evt]) { // 若是未监放任何事件,直接中断 return } for (let i = 0; i < events[evt].length; i++) { // 遍历,实现对同一个事件的屡次回调 events[evt][i].handler(args) } } function off(name) { delete events[name] } return { on: on, // 订阅者 fire: fire, // 发布者 off: off // 取消订阅 } })() EventCenter.on('hello', function (num) { console.log(num) }) EventCenter.on('hello', function (num) { console.log(num) }) EventCenter.fire('hello', 1) // 1[出现两次]