面向对象编程
1、封装
2、this
- 在函数执行的时候会在函数内部创建两个变量,arguments,this
- arguments 存储着实参的一个类数组对象
- this 指向函数的执行上下文{谁调用这个函数 this就指向谁}
3、call/apply
用于动态改变this指向
function aaa(name, age){
// console.log(this)
this.name = name
this.age = age
}
var objA = {
b: aaa
}
// aaa() // window
// objA.b() // objA
// aaa.call(objA) // objA
// objA.b.apply(window) // window
aaa.call(objA, 'xiaoA', 18)
console.log(objA.name, objA.age)
objA.b.apply(window, ['xiaoB', 28])
console.log(window.name, window.age)
4、new操作符
function CreateCat(name){
this.name = name
}
var catA = new CreateCat('xiaoA')
console.log(catA.name)
new 做了哪些
- 1、创建了一个控对象
- 2、将构造函数的
prototype属性赋值给新对象的__proto__属性
- 3、将构造函数的this指向新对象
- 4、执行构造函数的代码
- 5、将新对象返回
var catB = (function(){
var obj = {}
obj.__proto__ = CreateCat.prototype
CreateCat.call(obj, 'xiaoB')
return obj
})()
5、继承
1、在声明函数的时候,会自动创建一个prototype属性,我们称为原型,一般用来存放公用的方法
2、在JS里规定,访问对象属性的时候,如果对象下面没有这个属性,则去他下面的__proto__去寻找,如果还没有就一直向下寻找直到没有__proto__为止
function CreateCat(name){
this.name = name
}
CreateCat.prototype.eat = function(something){
console.log(this.name + 'eat' + something)
}
var catA = new CreateCat('xiaoA')
catA.eat('fish')
/*
catA: {
__proto__: CreateCat.prototype,
name: 'xiaoA'
}
*/
5.1类式继承(原型继承)
弊端
- 1、这种方法不支持父构造函数带参数
- 2、父构造函数里的方法和属性都会变成公有属性
function A(name){
this.name = name
this.list = [1,2,3]
}
A.prototype.getName = function(){
console.log(name)
}
function SubA(name) {
this.subName = 'sub' + this.name
}
SubA.prototype = new A() // 核心
var sub1 = new SubA('sub1')
console.log(sub1.list, sub1.name) // [1,2,3] undefined
/*
SubA.prototype = new A() -> {
name: undefined,
list: [1,2,3],
__proto__: {
getName: fn,
constructor
}
};
sub1 = new SubA('sub1') -> {
name: 'sub sub1',
__proto__: ==> SubA.prototype
}
*/
5.2构造函数继承
弊端
function A(name){
this.name = name
this.list = [1,2,3]
}
A.prototype.getName = function(){
console.log(name)
}
function SubA(name) {
A.call(this, name) // 核心
this.subName = 'sub' + this.name
}
var sub1 = new SubA('sub1')
console.log(sub1.name, sub1.subName)
sub1.getName() // 报错
/*
new SubA('sub1') --> {
__proto__: {constructor...},
name: 'xiaoA',
list: [1,2,3],
subName: 'sub xiaoA'
}
*/
5.3组合式继承
弊端
- 1、
__proto__里的属性重复了
- 2、执行了2次父构造函数
function A(name){
this.name = name
this.list = [1,2,3]
}
A.prototype.getName = function(){
console.log(name)
}
function SubA(name) {
A.call(this, name)
this.subName = 'sub' + this.name
}
SubA.prototype = new A() // 核心
var sub1 = new SubA('xiaoA')
console.log(sub1.name, sub1.subName)
sub1.getName()
/*
SubA.prototype = new A() -> {
name: undefined,
list: [1,2,3],
__proto__: {
getName: fn,
constructor
}
};
new SubA('xiaoA') --> {
__proto__: {
name: undefined,
list: [1,2,3],
__proto__: {
getName: fn,
constructor
}
},
name: 'xiaoA',
list: [1,2,3],
subName: 'sub xiaoA'
}
*/
5.4寄生组合式继承
function A(name){
this.name = name
this.list = [1,2,3]
}
A.prototype.getName = function(){
console.log(name)
}
function SubA(name) {
A.call(this, name)
this.subName = 'sub' + this.name
}
// 核心
function inheritPrototype(subClass, superClass){
function F(){}
F.prototype = superClass.prototype
subClass.prototype = new F()
subClass.prototype.constructor = subClass
}
inheritPrototype(SubA, A)
var sub1 = new SubA('xiaoA')
console.log(sub1.name, sub1.subName)
sub1.getName()
6、多态
多态:表示不同对象调用相同方法会产生不同结果
function Base(){}
Base.prototype.inital = function(){
this.init()
}
function SubA(){
this.init = function(){
console.log('SubA init')
}
}
function SubB(){
this.init = function(){
console.log('SubB init')
}
}
SubA.prototype = new Base()
SubB.prototype = new Base()
var subA = new SubA()
var subB = new SubB()
subA.inital()
subB.inital()
工厂模式
用来创建对象的
简单的工厂模式
function createPerson(name){
var o = {}
o.name = name
o.getName = function(){
console.log(this.name)
}
return o
}
var p1 = createPerson('张三')
p1.getName()
复杂的工厂模式
function Person(name){
this.name = name
}
Person.prototype.getName = function(){
console.log(this.name)
}
function Car(model){
this.model = model
}
Car.prototype.getModel = function(){
console.log(this.model)
}
function Create(type, param){
// return new this[type](param)
if(this instanceof Create){ // instanceof会判断后面的构造函数的原型,是不是存在在前面这个对象的原型链里
return new this[type](param)
} else {
return new Create(type, param)
}
}
Create.prototype = {
person: Person,
car: Car
}
var p1 = new Create('person', '张三')
var c1 = Create('car', '奔驰')
p1.getName()
c1.getModel()
/*
new Create('person', '张三') --> {
__proto__: Create.prototype
}
new this[type](param) --> new Person('张三') --> {
__proto__: Persopn.prototype,
name: '张三'
}
*/
建造者模式
注重创建对象的细节,用于创建出复杂对象或者复合对象
var data = [
{
name: '张三',
age: 23,
work: 'engineer'
},
...
]
// 普通写法
function Candidate(param){
var _candidate = {}
_candidate.name = param.name
_candidate.age = param.age
_candidate.firstName = _candidate.name.split(' ')[0]
_candidate.secondName = _candidate.name.split(' ')[1]
switch(param.work){
case 'engineer':
_candidate.work.name = '工程师'
_candidate.work.desc = '热爱编程'
break;
...
default:
_candidate.work.name = param.work
_candidate.work.desc = '无'
break;
}
_candidate.work.changeWork = function(work){
this.name = work
}
_candidate.work.changeDesc = function(desc){
this.desc = desc
}
var candidateArr = []
for(var i = 0; i < data.lenght; i++){
candidateArr[i] = Candidate(data[i])
}
console.log(candidateArr)
candidateArr[0].work.changeWork('xxx')
}
// 建造者模式
function Candidate(param){
var _candidate = new Person()
_candidate.name = new CreateName(param.name)
_candidate.eork = new CreateWork(param.work)
return _candidate
}
function Person(param){
this.name = param.name
this.age = param.age
}
function CreateName(name){
this.wholeName = name
this.firstName = name.split(' ')[0]
this.secondName = name.split(' ')[1]
}
function CreateWork(work){
switch(work){
case 'engineer':
this.name = '工程师'
this.desc = '热爱编程'
break;
...
default:
this.name = work
this.desc = '无'
break;
}
}
CreateWork.prototype.changeWork = function(work){
this.name = work
}
CreateWork.prototype.changeDesc = function(desc){
this.desc = desc
}
var candidateArr = []
for(var i = 0; i < data.lenght; i++){
candidateArr[i] = Candidate(data[i])
}
console.log(candidateArr)
candidateArr[0].work.changeWork('xxx')
单例模式
使用方法创建对象的时候,我们无论创建多少次对象都指向同一个
简单
function notSingle(){
return {
a: 1
}
}
var a = notSingle()
var b = notSingle()
console.log(a===b) // false
function notSingle2(){
this.a = 123
}
var a1 = new notSingle2()
var b1 = new notSingle2()
console.log(a===b) // false
/*
以上表明无论用函数还是构造函数,创建出的对象都是独立的
*/
安全
var _unique = null // 核心:缓存一个对象
function createSingle(){
var obj = {
a: 1
}
if(_unique === null){
_unique = obj
}
return _unique
}
var a = createSingle()
// _unique = null // 可以让单例失效
var b = createSingle()
console.log(a===b) // true
// 安全的单例模式,使用闭包,将_unique私有
var createSingle = (function(){
var _unique = null
function single(){
return {
a: 1
}
}
return function(){
if(_unique === null){
_unique = single()
}
return _unique
}
})()
var a = createSingle()
var b = createSingle()
console.log(a===b) // true
装饰器模式
希望在不改变原对象的基础上,通过对其拓展功能和属性来实现更复杂的逻辑
一般写法
function Car(){
this.price = 10
}
Car.prototype = {
addHeatSeat: function(){
this.hasHeatSeat = true
this.price += 2
},
addAutoMirror: function(){
this.hasAutoMirror = true
this.price += 0.8
}
}
var car1 = new Car()
console.log(car1.price)
car1.addHeatSeat()
car1.addAutoMirror()
console.log(car1.price)
装饰器写法
function Car(){
this.price = 10
}
function carWithHeatSeat(carClass){
carClass.hasHeatSeat = true
carClass.price += 2
}
function carWithAutoMirror(carClass){
carClass.hasAutoMirror = true
carClass.price += 0.8
}
var car2 = new Car()
console.log(car2.price)
carWithHeatSeat(car2)
carWithAutoMirror(car2)
console.log(car2.price)
组合模式
将多个部分通过组合变成一个整体。
window.onload = function () {
// 组合寄生式继承
function inheritPrototype(subClass, superClass) {
function F(){}
F.prototype = superClass.prototype
subClass.prototype = new F()
subClass.prototype.constructor = subClass
}
// 基类
function Container() {
this.children = []
this.element = null
}
Container.prototype = {
init: function () {
throw new Error('重写init方法')
},
add: function (child) {
this.children.push(child)
this.element.appendChild(child.element)
}
}
// 基于容器基类创建表单容器
function CreateForm(id, method, action, parent) {
Container.call(this)
this.id = id || ''
this.method = method || 'get'
this.action = action || ''
this.parent = parent
this.init()
}
inheritPrototype(CreateForm, Container)
CreateForm.prototype.init = function () {
this.element = document.createElement('form')
this.element.id = this.id
this.element.method = this.method
this.element.action = this.action
}
CreateForm.prototype.show = function () {
this.parent.appendChild(this.element)
}
// 行容器组件
function CreateLine(className) {
Container.call(this)
this.className = className === undefined ? 'form-line' : 'form-line' + className
this.init()
}
inheritPrototype(CreateLine, Container)
CreateLine.prototype.init = function () {
this.element = document.createElement('div')
this.element.className = this.className
}
// label组件
function CreateLable(text, forName) {
this.text = text || ''
this.forName = forName || ''
this.init()
}
CreateLable.prototype.init = function () {
this.element = document.createElement('label')
this.element.setAttribute('for', this.forName)
this.element.innerHTML = this.text
}
// input组件
function CreateInput(type, id, name, defaultValue) {
this.type = type || ''
this.id = id || ''
this.name = name || ''
this.defaultValue = defaultValue || ''
this.init()
}
CreateInput.prototype.init = function () {
this.element = document.createElement('input')
this.element.type = this.type
this.element.id = this.id
this.element.name = this.name
this.element.defaultValue = this.defaultValue
}
// 使用
var form = new CreateForm('ownerForm', 'GET', '/aaa.html', document.body)
var useLine = new CreateLine()
useLine.add(new CreateLable('用户名', 'user'))
useLine.add(new CreateInput('text', 'user', 'user'))
var pwdLine = new CreateLine()
pwdLine.add(new CreateLable('密码', 'pwd'))
pwdLine.add(new CreateInput('password', 'pwd', 'pwd'))
var submitLine = new CreateLine()
submitLine.add(new CreateInput('submit', '', '', '登录'))
form.add(useLine)
form.add(pwdLine)
form.add(submitLine)
form.show()
}
观察者模式(发布订阅模式/消息模式)
定义一个主体(消息中心):各种不同的消息
定义多个个体:订阅不同的消息,当主体发布某条消息,则会收到通知
var msgCenter = (function () {
var _msg = {} // 存储消息
/*
_msg = {
'carInfo': [p1.alreadyRegister.carInfo, p2.alreadyRegister.carInfo, p3.alreadyRegister.carInfo],
'newInfo': [p1.alreadyRegister.newInfo]
}
*/
return {
register: function (type, fn) { // 用于订阅一个消息
if (_msg[type]) {
_msg[type].push(fn)
} else {
_msg[type] = [fn]
}
},
fire: function (type, args) { // 用于发布消息
if (!_msg[type]) {
return
}
var event = {
type: type,
args: args || {}
}
for (var i = 0; i < _msg[type].length; i++) {
_msg[type][i](event);
}
},
cancel: function (type, fn) { // 用于取消订阅消息
if (!_msg[type]) {
return
}
for (var i = 0; i < _msg[type].length; i++) {
if (_msg[type][i] === fn) {
_msg[type][i].splice(i, 1)
break
}
}
},
}
})()
function Person() {
this.alreadyRegister = {}
}
Person.prototype.register = function (type, fn) {
if (this.alreadyRegister[type]) {
console.log('已订阅,重复')
} else {
msgCenter.register(type, fn)
this.alreadyRegister[type] = fn
}
}
Person.prototype.cancel = function (type) {
msgCenter.cancel(type, this.alreadyRegister[type])
delete this.alreadyRegister[type]
}
var p1 = new Person()
var p2 = new Person()
var p3 = new Person()
p1.register('carInfo', function (e) {
console.log('p1' + e.type + '---' + e.args.info)
})
p1.register('newInfo', function (e) {
console.log('p1' + e.type + '---' + e.args.info)
})
p2.register('carInfo', function (e) {
console.log('p2' + e.type + '---' + e.args.info)
})
p3.register('carInfo', function (e) {
console.log('p3' + e.type + '---' + e.args.info)
})
msgCenter.fire('carInfo', {
info: '新款上市'
})
msgCenter.fire('newInfo', {
info: '最新消息'
})
p1.register('carInfo', function (e) {
console.log('p1' + e.type + '---' + e.args.info)
})
策略模式
用在有多种状态或者策略需要进行选择的时候,将所有选择封装在一起,只给外部暴露出必要的接口
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论