Javascript设计模式 从零开始(基础篇

Javascript 设计模式从零开始(基础篇

前端时间,有幸拜读了曾探所著的《Javascript设计模式与开发实践》一书,做一些笔记加深理解,读了有没有用俺不知道,反正我觉得这本书写挺好

1、对象及原型链

Js创建对象的方法

var obj = { }

在js里函数也是对象,所以可以使用 function 创建对象

function obj(name){
	this.name = name
}

var newObj = new obj('foo')

es6中使用 class 来定义对象,其本质上与函数式没有区别

class ClassName {
	constructor(name){
		this.name = name
	}
}

var newClass = new ClassName('bar')

console.log(typeof ClassName);//  function

原型链
新建一个index.js,通过index.hmtl 引用使用Chrome浏览器查看输出结果

function FunctionName(name){
  this.name = name
}

var newFunction = new FunctionName('foo')


class ClassName{
  constructor(name){
    this.name = name
  }
}

var newClass = new ClassName('bar')


console.log('ClassName.__proto__:')
console.log(ClassName.__proto__)
console.log('函数才有prototype ClassName.prototype:')
console.log(ClassName.prototype)

console.log('FunctionName.__proto__:')
console.log(FunctionName.__proto__)
console.log('FunctionName.prorotype:')
console.log(FunctionName.prototype)


//console.log(newClass)
console.log("newClass.__proto__:")
console.log(newClass.__proto__)
console.log('实例没有 prototype:')
console.log(newClass.prototype)

console.log(newClass.__proto__ === ClassName.prototype) //true

所有的引用类型(包含实例)都有一个__proto__ 隐藏属性指向构建函数的prototype
所有的构造函数都有一个protype属性指向原型对象
当查找对象属性时会先在对象属性上查找,如果找不到就会在原型上查找,知道找到null 为止

2、this call和applay

Js上的this 一直是令人迷惑的问题之一
1、函数作为对象的方法被调用时,this指向当前对象
2、在普通函数中this指向 window
3、在箭头函数中this 继承自父执行环境上下文的this

var name = 'window'
var = obj ={
	name: 'obj',
	age: '20',
	getName: () => {
	  console.log(this.name) //window
	  
	}
	getAge
}

在这个例子中 箭头函数与getName 平级,在obj中被定义,继承自obj的this 故指向 window
箭头函数没有自己的this不能用作构造函数

使用 apply 和 call 改变this指向
call 和 apply 作用相同但传参的形式不同
func.call(null,1,2,3)
func.call(null,[1,2,3])

var obj1 = function(){
	this.name = 'obj1',
	
}

var obj2 = function(){
	this.name = 'obj2'
}

var getName = function(){
	console.log(this.name)
}

getName.call(obj1)
getName.call(obj2)

使用 apply 和 call 实现继承(盗用函数)

var Person = function(name){
	this.name = name,
	this.getName = function(){
		console.log(this.name)
	}
}

var Son = function(name){
	Person.call(this,name)
}

var xiaoMing = new Son('小明')

xiaoMing.getName()

3、闭包

闭包一般是指函数内部的函数
闭包可用于封装私有变量
应用实例,函数节流

 function throttle(func,delay){
 let result
 return function(){
     let context = this
     let args = arguments
 	if(!timer){
 	   timer = setTimeout(function(){
 	       result = func.apply(context,args)
 	   },delay)
 	}
 	
 	return result
 }
}

const handle = function(){
  console.log('some request')
}
window.addEventListener(scroll,functuon(){
  throttle(handle,500)
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值