1. 封装和继承
- 并不是封装继承和多态,而是写代码的套路问题(定势思维)
2. 原型链(对象与对象关系)
2.1 七种数据类型
- 基本类型,存值:number/string/bool/undefined/null/symbol
- 引用类型,存内存地址:object
2.2 原型链
2.2.1 具体对象的__proto__/[[Prototype]]
- __proto__这个属性其实指向了[[Prototype]],但是[[Prototype]]是内部属性,我们并不能访问到,所以使用__proto__来访问
var obj = {'name': 'a', age: 18}
var obj2 = {name: 'b', age: 20}
console.dir(obj)
console.dir(obj2)
obj.__proto__ === obj2.__proto__
obj.__proto__.gender = '男'
boj2.gender


2.2.2 Object的prototype
window.Object.prototype
obj.__proto__ === Object.prototype
arr.__proto__ === Array.prototype
pro.__proto__ === Promise.prototype
arr.__proto__.__proto__ === Object.prototype
Array.__proto__ === Object.prototype
Array.prototype.__proto__ === Object.prototype
Function.prototype.__proto__ === Object.prototype

3. this(对象与函数联系)
- 函数是一种可执行代码(eval执行字符串)组成的对象
var obj = {
name: 'paul',
sayName: function() {
console.log('I am', this.name)
}
}
obj.sayName()
obj.sayName.call()
obj.sayName.call({name: 'james'})
var baba = {
name: 'Mayun',
child: {
name: 'Sicong',
sayName: function() {
'use strict'
console.log(this.name)
}
}
}
baba.child.sayName()
baba.child.sayName.call()
baba.child.sayName.call(baba)
- 箭头函数的this,找上级
- this执行时候才能确定
4. bind
- bind方法创建一个新的函数,当被调用时,将其this关键字设置为提供的值
- bind参数也是this,参数,非调用,创建了新函数
5. new
- 批量创建对象
- 匿名函数新创建堆,有名函数可以复用
- 返回新对象的函数就是构造函数
- JS 的 new 到底是干什么的?
- 构造函数首字母大写
- 如果构造函数没有参数,那么可以省略括号 new XXX
1. 构造函数首字母大写
2. 构造函数可以省掉 create
3. 如果构造函数没有参数,那么可以省略括号
function Soldier(name){
this.ID = i
this.生命值 = 42
this.name = name || '无名战士'
}
Soldier.prototype.兵种 = "美国大兵"
Soldier.prototype.攻击力 = 5
Soldier.prototype.行走 = function(){ },
Soldier.prototype.奔跑 = function(){ },
Soldier.prototype.死亡 = function(){ },
Soldier.prototype.攻击 = function(){ },
Soldier.prototype.防御 = function(){ }
var soldiers = []
for(var i=0; i<100; i++){
soldiers.push( new Soldier )
}
兵营.batchMake(soldiers)
6. 继承的写法
士兵 extend 人类
s = new 士兵
function Human(options){
this.name = options.name
this.肤色 = options.肤色
}
Human.prototype.eat = function(){}
Human.prototype.drink = function(){}
Human.prototype.poo = function(){}
function Soldier(options){
Human.call(this, options)
this.ID = options.ID
this.生命值 = 42
}
Soldier.prototype = Object.create(Human.prototype)
Soldier.prototype.兵种 = "美国大兵"
Soldier.prototype.攻击力 = 5
Soldier.prototype.行走 = function(){ },
Soldier.prototype.奔跑 = function(){ },
Soldier.prototype.死亡 = function(){ },
Soldier.prototype.攻击 = function(){ },
Soldier.prototype.防御 = function(){ }
var s = new Soldier({name: '方方', 肤色:'yellow', ID: 1})
- class写法
- extends只继承公有属性
- super的意思是call调用一下父类Humen
class Human{
constructor(options){
this.name = options.name
this.肤色 = options.肤色
}
eat(){}
drink(){}
poon(){}
}
class Soldier extends Human{
constructor(options){
super(options)
this.ID = options.ID
this.生命值 = 42
this.兵种 = "美国大兵"
this.攻击力 = 5
}
行走(){ }
奔跑(){ }
死亡(){ }
攻击(){ }
防御(){ }
}
var s = new Soldier({name: '方方', 肤色:'yellow', ID: 1})
