面向对象编程
new 运算符
- 执行函数;
- 自动创建空对象
- 把创建的对象指向另一个对象
- 吧空对象和函数里的this衔接起来(this指向实例化对象)
- 隐式返还this
1 2 3 4 5 6 7 8
| function test(){ console.log("test....") }
test(); new test; new test();
|
简化工厂模式 —–> 构造函数
约定俗成 : 首字母大写
属性放在构造原型;方法放在原型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| function Tab(){ this.name = "张三"; this.hobby = function(){ console.log("篮球"); } } let tab1 = new Tab();
console.log(tab1.__proto__===Tab.prototype) console.log(Tab.prototype.__proto__===Object.prototype) console.log(Object.prototype.__proto__)
Tab.prototype.psFor = function(){ console.log('psFor...') }
let tab2 = new Tab(); console.log(tab1.psFor === tab2.psFor)
Tab.prototype.foods = function(){ console.log(this.name,'foods...') }
tab1.foods()
|
每个原型上都有一个预定义属性 : constructor
覆盖原本的 constructor 属性
用以下写法必须要写constructor,不然会找不到对象的原型指向
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| Tab.prototype={ constructor:Tab, psFor(){ console.log('psFor...') }, hobby(){ console.log('hobby...') } }
let str = '123saar' if(str.constructor===String){ console.log("字符串") }else{ console.log("不是") }
|
es6 类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Drag{ static height = "178cm"; constructor(age){ this.name = "张三" this.age = age } hobby(){ console.log("篮球") } setStyle(){ console.log("父类逻辑") } testSuper(){ console.log("父类test逻辑") } }
Drag.test = function(){ console.log('test...') }
Drag.test()
console.log(Drag.height)
console.log(typeof Drag) let drag1 = new Drag()
|
继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class LimitDrag extends Drag{ constructor(age){ super(age); } setStyle(){ console.log("子类逻辑") } testSuper(){ super.testSuper() console.log("子类test逻辑") } } let drag2 = new LimitDrag(20)
console.log(LimitDrag.height) console.log(drag2.height)
drag2.setStyle() drag2.testSuper()
|