Blogger Information
Blog 22
fans 0
comment 1
visits 17602
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
第十二章面向对象编程
刘静的博客
Original
986 people have browsed it

第十二章面向对象编程

本章内容介绍

面向对象编程

1.对象是什么?

2.构造函数

new

constructor

3.原型对象

4.创建对象的5中模式

对象字面量

工厂模式

构造函数模式

原型模式

组合模式

5.实现继承的5种方式

6.选项卡(面向对象)

对象的定义

面向对象编程(OOP):具有灵活,代码可复用性,高度模块化等特点

[^OOP:object oriented programming]:

1.对象是单个实物的抽象

2.对象是一个容器,封装了对应属性和方法

属性是对象的状态,方法是对象的行为(完成的任务)

构造函数实例化对象

需要一个模板(表示一类实物的共同特征),让对象生成

类 (class) 就是对象的模板

[^js不是基于类的,而是基于构造函数(constructor)和原型链(prototype)]:

特点:

1.函数体内使用this关键字,代表了所要生成的对象实例

2.生成对象,必须使用new关键字实例化

  1. function Dog(name,age){
  2. 'use strict';
  3. // name和age就是当前实例化对象的属性
  4. this.name = name;
  5. this.age = age;
  6. }
  7. var dog1 = new Dog('阿黄',10);
  8. var d = Dog('阿黄',10);
  9. console.log(d);//undefined

[^Dog是构造函数,为了与普通函数区别,构造函数的名字的第一个字母通常都大写]:

  1. function Person(name){
  2. if(this instanceof Person){
  3. // this指向了当前的实例,外部使用了关键字new
  4. this.name = name;
  5. }else{
  6. // this指向了window,外部没有使用了关键字new
  7. return new Person(name);
  8. }
  9. }
  10. var p1 = new Person('mjj');
  11. var p2 = Person('mjj');
  12. console.log(p1);
  13. console.log(p2);

[^a instanceof A a是否是A的一个实例]:

new命令内部原理

new命令的原理

1.创建一个空对象,作为将要返回的对象实例

2.将这个空的对象原型对象,指向了构造函数的prototype属性对象

3.将这个实例对象的值赋值给函数内部的this关键字

4.执行构造函数体内的代码

  1. function Person(name){
  2. this.name = name;
  3. }
  4. var p1 = new Person('mjj');
  5. // console.log(Person.prototype);
  6. console.log(p1.__proto__ === Person.prototype);
  7. console.log(Person.prototype);
  8. var p1 = function Person(name){
  9. this.name = name;
  10. };
  11. Person.prototype = p1.__proto__;

constructor属性

每个对象在创建时都会自动拥有一个构造函数属性constructor

  1. function Person(name){
  2. this.name = name;
  3. }
  4. var p1 = new Person('mjj');
  5. console.log(p1);
  6. // constructor继承自原型对象,指向了构造函数的引用
  7. console.log(p1.constructor === Person);
  8. console.log(Person.prototype);

使用构造函数创建对象的利与弊

  1. <script type="text/javascript">
  2. function Person(name) {
  3. this.name = name;
  4. this.sayName = function() {
  5. console.log(this.name);
  6. }
  7. }
  8. var p1 = new Person('Tom');
  9. var p2 = new Person('Jack');
  10. console.log(p1,p2);
  11. </script>

生成两个Person空间,造成资源浪费

原型对象介绍

原型对象:Foo.prototype

实例对象: f1就是实例对象,每一个原型对象中都有一个proto,每个实例对象都有一个constructor属性,这个constructor通过继承关系继承来的,它指向了当前的构造函数Foo

构造函数:用来初始化新创建对象的函数,Foo是构造函数,自动给构造函数赋予一个属性prototype,该属性指向了实例对象的原型对象

  1. function Foo(){};//Foo是构造函数;自动赋予属性Foo.prototype
  2. Foo.prototype.showName = function(){
  3. console.log('mjj');
  4. };
  5. var f1 = new Foo();//f1.__proto__(f1的原型对象);f1.constructor
  6. var f2 = new Foo();
  7. console.log(f1.showName());
  8. console.log(f2.showName());

理清原型对象实例对象构造函数之间的关系![理清原型对象实例对象构造函数之间的关系]

  1. <script type="text/javascript">
  2. function Foo(){};
  3. var f1 = new Foo();
  4. console.log(Foo.prototype === f1.__proto__)//true
  5. console.log(f1.__proto__.__proto__)//object实例
  6. console.log(f1.__proto__.__proto__.__proto__)//null
  7. </script>

prototype属性的作用

js继承机制:通过原型对象实现继承

[^原型对象的作用,就是定义所有实例对象共享的属性和方法]:

  1. function Foo(){};
  2. Foo.prototype.name = 'mjj';
  3. var f1 = new Foo();
  4. var f2 = new Foo();
  5. console.log(f1.name);//mjj
  6. console.log(f2.name);//mjj
  7. Foo.prototype.name = 'alex';
  8. console.log(f1.name);//alex
  9. console.log(f2.name);//alex

原型链挖掘

js规定,所有的对象都有自己的原型对象

[^原型链:对象的原型=>原型的原型=>原型的原型的原型======null]:
[^根据原型链查找,如果一层一层往上查找,所有对象的原型最终都可以寻找到Object.prototype,Object构造函数的prototype]:

所有的对象都继承了Object.prototype上的属性和方法,例如:toString()

读取属性和方法的规则:

js引擎会先寻找对象本身的属性和方法,如果找不到.就到它的原型对象去找,如果还是找不到,就到原型的原型去找,如果直到最顶层的Object.prototype还是找不到,就会返回undefined

[^如果对象和它的原型,都定制了同名的属性,那么优先读取对象自身的属性,这也叫覆盖]:

  1. function Person(name){
  2. this.name = name;
  3. this.showName = function(){
  4. console.log('小猿');
  5. }
  6. }
  7. Person.prototype.showName = function(){
  8. console.log(this.name);
  9. }
  10. Object.prototype.showAge = function(){
  11. console.log('24');
  12. }
  13. var p1 = new Person('mjj');
  14. var p2 = new Person('alex');
  15. p1.showName();
  16. p2.showName();
  17. console.log(p1.age);
  18. p1.showAge();
  19. var arr = [12,3,4];
  20. arr.showAge()

修改原型对象后constructor属性的注意点

一旦我们修改构造函数的原型对象,为防止引用出现问题,同时也要修改原型对象的constructor属性

[^constructor属性表示原型对象和构造函数之间的关联关系,Foo.prototype.constructor = Foo]:

  1. function MyArray(){};
  2. MyArray.prototype = Array.prototype;
  3. // console.log(MyArray.prototype.constructor);
  4. MyArray.prototype.constructor = MyArray;
  5. var arr = new MyArray();
  6. console.log(arr);//MyArray{}
  7. arr.push(1,2,3);
  8. console.log(arr);//MyArray(3){1,2,3}
  9. console.log(arr.constructor);//MyArray(){}
  10. console.log(arr.__proto__ === MyArray.prototype);//true

原型对象构造函数实例对象总结

1.构造函数:Foo

2.实例对象:f1

3.原型对象:Foo.prototype

  1. function Foo(){};
  2. var f1 = new Foo();

1.原型对象和实例对象的关系

  1. console.log(Foo.prototype === f1.__proto__);

2.原型对象和构造函数的关系

  1. console.log(Foo.prototype.constructor === Foo);

3.实例对象和构造函数

[^间接关系是实例对象可以继承原型对象的constructor属性]:

  1. console.log(f1.constructor === Foo);
  2. Foo.prototype = {};//重置原型对象
  3. console.log(Foo.prototype);//{} constructor: ƒ Object()
  4. console.log(Foo.prototype === f1.__proto__);//false
  5. console.log(Foo.prototype.constructor === Foo);//false
  6. // 所以,代码的顺序很重要

构造函数创建方式

1.对象字面量方式

1.1new构造函数

  1. var obj = new Object();
  2. obj.name = '小猿';
  3. console.log(obj);

1.2对象字面量 (语法糖)

  1. var person1 = {
  2. name:"MJJ",
  3. age:29
  4. }
  5. var person2 = {
  6. name:"MJJ",
  7. age:29
  8. }
  9. var person3 = {
  10. name:"MJJ",
  11. age:29
  12. }
  13. var person4 = {
  14. name:"MJJ",
  15. age:29
  16. }
  17. console.log(person);
  18. console.log(person.name);

1.3Object.create(对象)

需求:从一个实例对象生成另一个实例对象

[^create()中的参数a作为返回实例对象b的的原型对象,在a中定义的属性方法,都能被b实例对象继承下来]:

  1. var a = {
  2. getX:function(){
  3. console.log('X');
  4. }
  5. }
  6. var b = Object.create(a);//a作为b的原型对象
  7. b.getX();

2.工厂模式

特点:能创建多个类似的对象

缺点:没有解决对象识别的问题,使用构造函数模式解决

  1. <script type="text/javascript">
  2. function createPerson(name,age){
  3. var o = new Object();
  4. o.name = name;
  5. o.age = age;
  6. o.sayName = function (){
  7. console.log(this.name);
  8. }
  9. return o;
  10. }
  11. var p1 = createPerson('mjj',18);
  12. var p2 = createPerson('alex',38);
  13. p1.sayName();
  14. console.log(p1 instanceof Object);
  15. console.log(p2 instanceof Object);
  16. </script>

3.构造函数模式

一般构造函数模式

缺点:浪费了内存空间

  1. <script type="text/javascript">
  2. function Person(name,age){
  3. this.name = name;//this指向实例对象(man/woman)
  4. this.age = age;
  5. this.sayName = function(){
  6. console.log(this.name);
  7. }
  8. }
  9. var man = new Person('mjj',18);
  10. var woman = new Person('alex',38);
  11. // 具有相同的sayName方法在man和woman实例中占用了不同的内存空间
  12. console.log(man.sayName === woman.sayName);
  13. </script>

3.1构造函数拓展模式

缺点:定义多个全局函数,严重污染全局空间

  1. function Person(name,age){
  2. this.name = name;
  3. this.age = age;
  4. this.sayName = sayName;
  5. }
  6. function sayName(){
  7. console.log(this.name);
  8. }
  9. var man = new Person('mjj',18);
  10. var woman = new Person('alex',38);
  11. console.log(man.sayName === woman.sayName);//false,代表创建了两个sayName函数对象

3.2寄生构造函数模式(工厂模式和构造函数模式)

创建一个函数,函数体内部实例化一个对象,并且将对象返回,在外部的使用使用new来实例化对象

缺点:1.定义了相同的方法,浪费内存空间;2.instanceof运算符和prototype属性都没有意义

[^该模式尽量避免使用]:

  1. function Person(name,age){
  2. var o = new Object();
  3. o.name = name;
  4. o.age = age;
  5. o.sayName = function(){
  6. console.log(this.name);
  7. }
  8. return o;
  9. }
  10. var man = new Person('mjj',18);
  11. var woman = new Person('alex',38);
  12. console.log(man.sayName === woman.sayName);//false,代表创建了两个sayName函数对象
  13. console.log(man.__proto__ === Person.prototype);//false
  14. console.log(man instanceof Person);//false

会造成空间浪费

3.3稳妥构造函数模式

稳妥模式:没有公共属性,并且它的方法也不引用this对象

[^instancof prototype属性都不能适用]:

  1. function Person(name){
  2. var a = 10;
  3. var o = new Object();
  4. // name就属于私有属性 结合闭包 让数据安全
  5. o.sayName = function(){
  6. console.log(a);//10
  7. console.log(name);//mjj
  8. }
  9. return o;
  10. }
  11. // p1对象叫稳妥对象
  12. var p1 = Person('mjj');
  13. var p2 = Person('mjj2');
  14. p1.sayName();//false
  15. console.log(p1.sayName === p2.sayName);//没有结果

4.原型模式

缺点:在于引用类型值属性会被所有的实例对象共享并且修改,很少适用原型模式的原因

  1. function Person(){};
  1. 第一种写法:
  2. Person.prototype.name = 'mjj';
  3. Person.prototype.age = 28;
  4. Person.prototype.sayName = function(){
  5. console.log(this.name);
  6. }
  1. 第二种写法:
  2. Person.prototype = {
  3. constructor:Person,
  4. name:'mjj',
  5. age:28,
  6. friends:['alex','阿黄'],
  7. sayName:function(){
  8. console.log(this.name);
  9. }
  10. }
  1. //Person.prototype.constructor = Person;
  2. var me = new Person();
  3. me.sayName();
  4. var you = new Person();
  5. you.sayName();
  6. me.friends.push('小红');
  7. console.log(me.friends);
  8. console.log(you.friends);//其他实例也会修改
  9. //console.log(me.constructor === Person);

5.组合模式

特点:该模式是目前使用最广泛,认同度最高的一种创建自定义对象的模式

  1. function Person(name,age){
  2. // 定制当前对象自己的属性
  3. this.name = name;
  4. this.age = age;
  5. this.friends = ['alex','阿黄'];
  6. };
  7. // 定制各个实例对象的共享属性
  8. Person.prototype = {
  9. // 改变原型对象的同时要改变该原型对象的constructor属性,让它指向了当前的构造函数Person
  10. constructor:Person,
  11. sayName:function(){
  12. console.log(this.name);//21
  13. }
  14. }
  15. var wo = new Person('wo',18);
  16. var you = new Person('you',28);
  17. console.log(wo,you);//26
  18. wo.friends.push('小红');
  19. console.log(wo.friends);//28
  20. console.log(you.friends);//29
  21. wo.sayName();//21
  22. you.sayName();//21

6.动态原型模式

特点:该模式是目前使用最广泛,认同度最高的一种创建自定义对象的模式

  1. function Person(name, age) {
  2. // 定制当前对象自己的属性
  3. this.name = name;
  4. this.age = age;
  5. this.friends = ['alex', '阿黄'];
  6. if(typeof this.sayName != 'function'){
  7. // 初始化原型对象上的属性
  8. Person.prototype.sayName = function(){
  9. console.log(this.name);
  10. }
  11. }
  12. };
  13. console.log(Person.prototype);//object
  14. var wo = new Person('mjj',18);
  15. console.log(Person.prototype);
  16. console.log(wo instanceof Person);

基于面向过程的选项卡样式实现

css代码:

  1. <style type="text/css">
  2. *{
  3. padding:0px;
  4. margin:0px;
  5. }
  6. ul{
  7. list-style:none;
  8. overflow: hidden;
  9. border:1px solid #3081BF;
  10. width:300px;
  11. height:40px;
  12. line-height:40px;
  13. }
  14. a{
  15. text-decoration:none;
  16. }
  17. body{
  18. background:#B49B8B;
  19. }
  20. #wrap{
  21. width:302px;
  22. height:402px;
  23. margin:100px auto;
  24. }
  25. #wrap ul li{
  26. float:left;
  27. width:100px;
  28. height:100%;
  29. }
  30. #wrap ul li.active{
  31. background-color:#3081BF;
  32. font-weight:bold;
  33. }
  34. #wrap ul li a{
  35. display:block;
  36. width:100%;
  37. height:100%;
  38. color:#262626;
  39. font-size:18px;
  40. text-align:center;
  41. }
  42. div.content{
  43. width:300px;
  44. height:360px;
  45. border:1px solid #3081BF;
  46. display:none;
  47. }
  48. </style>

html代码

  1. <div id="wrap">
  2. <ul>
  3. <li class="active">
  4. <a href="javascript:void(0);">推荐</a>
  5. </li>
  6. <li>
  7. <a href="javascript:void(0);">小说</a>
  8. </li>
  9. <li>
  10. <a href="javascript:void(0);">导航</a>
  11. </li>
  12. </ul>
  13. <div class="content" style="display:block;">推荐</div>
  14. <div class="content">小说</div>
  15. <div class="content">导航</div>
  16. </div>

javascript代码

一般写法:

  1. <script type="text/javascript">
  2. window.onload = function(){
  3. //1.获取事件源
  4. // var tablis = document.getElementsByTagName('li');
  5. var wrap = document.getElementById('wrap');//事件委托
  6. var tablis = wrap.children[0].getElementsByTagName('li');
  7. // var contentDivs = document.getElementsByClassName('content');
  8. var contentDivs = wrap.getElementsByTagName('div');
  9. //2.绑定事件
  10. //一般写法
  11. for(var i =0;i<tablis.length;i++){
  12. //绑定i的索引
  13. tablis[i].index = i;
  14. tablis[i].onclick = function(){
  15. //去掉所有
  16. for(var j=0;j<tablis.length;j++){
  17. tablis[j].className = '';
  18. contentDivs[j].style.display = 'none';
  19. }
  20. this.className='active';
  21. contentDivs[this.index].style.display = 'block';
  22. }
  23. }
  24. }
  25. </script>

闭包写法

  1. <script type="text/javascript">
  2. window.onload = function(){
  3. //1.获取事件源
  4. // var tablis = document.getElementsByTagName('li');
  5. var wrap = document.getElementById('wrap');//事件委托
  6. var tablis = wrap.children[0].getElementsByTagName('li');
  7. // var contentDivs = document.getElementsByClassName('content');
  8. var contentDivs = wrap.getElementsByTagName('div');
  9. //2.绑定事件
  10. for(var i =0;i<tablis.length;i++){
  11. tablis[i].onclick = (function(n){
  12. return function(){
  13. //去掉所有
  14. for(var j=0;j<tablis.length;j++){
  15. tablis[j].className = '';
  16. contentDivs[j].style.display = 'none';
  17. }
  18. this.className='active';
  19. contentDivs[n].style.display = 'block';
  20. }
  21. })(i);
  22. }
  23. }
  24. </script>

封装函数写法

  1. <script type="text/javascript">
  2. window.onload = function(){
  3. //1.获取事件源
  4. // var tablis = document.getElementsByTagName('li');
  5. var wrap = document.getElementById('wrap');//事件委托
  6. var tablis = wrap.children[0].getElementsByTagName('li');
  7. // var contentDivs = document.getElementsByClassName('content');
  8. var contentDivs = wrap.getElementsByTagName('div');
  9. //2.绑定事件
  10. for(var i =0;i<tablis.length;i++){
  11. //绑定i的索引
  12. tablis[i].index = i;
  13. tablis[i].onclick = clickFun;
  14. }
  15. function clickFun(){
  16. //去掉所有
  17. for(var j=0;j<tablis.length;j++){
  18. tablis[j].className = '';
  19. contentDivs[j].style.display = 'none';
  20. }
  21. this.className='active';
  22. contentDivs[this.index].style.display = 'block';
  23. }
  24. }
  25. </script>

基于面向对象实现选项卡

基于面向对象实现选项卡写法流程如下:

1.构造函数

2.属性属于实例的属性

3.添加到原型上prototype

javascript代码

  1. <script src="js/TabSwitch.js"></script>
  2. <script type="text/javascript">
  3. // 1.构造函数
  4. // 2.属性属于实例的属性
  5. // 3.添加到原型上prototype
  6. //对象:属性和方法
  7. window.onload = function(){
  8. var wrap = document.getElementById('wrap');//事件委托
  9. var tab = new TabSwitch(wrap);
  10. }
  11. </script>

TabSwitch.js封装代码:

  1. //1.构造选项卡的函数
  2. function TabSwitch(fatherObj){
  3. //保存this
  4. // console.log(this);//指向函数对象TabSwitch
  5. var _this = this;
  6. // console.log(_this);//指向函数对象TabSwitch
  7. //2.绑定实例属性
  8. this.tablis = fatherObj.children[0].getElementsByTagName('li');
  9. this.contentDivs = fatherObj.getElementsByTagName('div');
  10. for(var i=0;i<this.tablis.length;i++){
  11. //绑定i的索引
  12. this.tablis[i].index = i;
  13. this.tablis[i].onclick = function(){
  14. // console.log(this);//指向每个li对象
  15. _this.clickFun(this.index);
  16. }
  17. }
  18. }
  19. //3.绑定共享的方法
  20. TabSwitch.prototype.clickFun = function(index){
  21. console.log(this);//指向函数对象TabSwitch object,HTMLElement
  22. //去掉所有
  23. for(var j=0;j<this.tablis.length;j++){
  24. this.tablis[j].className = '';
  25. this.contentDivs[j].style.display = 'none';
  26. }
  27. this.tablis[index].className='active';
  28. this.contentDivs[index].style.display = 'block';
  29. }

对象创建总结

重点

1.字面量方式

问题:创建多个对象会造成冗余的代码

2.工厂模式

解决对象字面量方式创建对象的问题

问题:对象识别的问题

3.构造函数模式

解决工厂模式的问题

问题:方法重复被创建

4.原型模式

解决构造函数模式创建对象的问题

特点:在于方法可以被共享

问题:给当前实例定制的引用类型的属性会被所有的实例所共享

5.组合模式(构造函数和原型模式)

构造函数模式:定义实例属性

原型模式:用于定义方法和共享的属性,还支持向构造函数中传递参数。

该模式是使用最广泛,应用度最高的一种模式

了解部分

构造函数扩展模式

寄生构造函数模式

稳妥构造函数模式

动态原型模式

继承方式

1.原型链继承

继承:在原型对象的所有属性和方法,都能被实例所共享

定制Animal

  1. function Animal(){
  2. this.name = 'alex';
  3. this.colors = ['red','green','blue'];
  4. }
  5. Animal.prototype.getName = function(){
  6. return this.name;
  7. }

Dog类

  1. function Dog(){};

Dog继承了Animal

本质:重写原型对象,将一个父对象的属性和方法作为一个子对象的原型对象的属性和方法

  1. Dog.prototype = new Animal();
  2. Dog.prototype.constructor = Dog;
  3. var d1 = new Dog();
  4. var d2 = new Dog();
  5. console.log(d1.colors);
  6. console.log(d2.colors);
  7. d1.colors.push('purple');
  8. console.log(d1.colors);
  9. console.log(d2.colors);

缺点:

1.父类中的实例属性一旦赋值给子类的原型属性,此时这些属性都属于子类的共享属性

2.实例化子类型的时候,不能向父类型的构造函数传参

2.借用构造函数继承

经典继承:在子类的构造函数内部调用父类的构造函数

缺点:父类定义的共享方法不能被子类所继承下来

父类:

  1. function Animal(name){
  2. this.name = name;
  3. this.colors = ['red','green','blue'];
  4. }
  5. Animal.prototype.getName = function(){
  6. return this.name;
  7. }

子类:

  1. function Dog(name){
  2. // 继承了Animal
  3. // 当new实例的时候,内部构造函数中this指向了d1,然后在当前构造函数内部再去通过call再去调用构造函数,那么父类中的构造函数中的this指向了d1,但是方法不能被继承下来
  4. Animal.call(this,name);
  5. }
  6. var d1 = new Dog('阿黄');
  7. var d2 = new Dog('小红');
  8. d1.colors.push('purple');
  9. console.log(d1.name);//阿黄
  10. console.log(d1.colors);//Array(4)
  11. // console.log(d1.getName());

3.组合继承

父类

  1. function Animal(name) {
  2. this.name = name;
  3. this.colors = ['red', 'green', 'blue'];
  4. }
  5. Animal.prototype.getName = function() {
  6. return this.name;
  7. }

子类:

  1. function Dog(name) {
  2. // 继承了Animal
  3. // 让父类的实例属性继承下来,实例修改引用类型的值,另一个实例的引用类型的值不会发生变化
  4. Animal.call(this, name);
  5. }
  6. // 重写原型对象:把父类的共享方法继承下来
  7. Dog.prototype = new Animal();
  8. Dog.prototype.constructor = Dog;
  9. var d1 = new Dog('阿黄');
  10. var d2 = new Dog('阿红');

缺点:无论在什么情况下,都会调用父类构造函数两次(1.一个是我们初始化子类的原型对象的时候; 2.在子类构造函数内部调用父类的构造函数)

4.寄生组合式继承

父类

  1. function Animal(name) {
  2. this.name = name;
  3. this.colors = ['red', 'green', 'blue'];
  4. }
  5. Animal.prototype.getName = function() {
  6. return this.name;
  7. }

子类

  1. function Dog(name) {
  2. // 继承了Animal
  3. // 让父类的实例属性继承下来,实例修改引用类型的值,另一个实例的引用类型的值不会发生变化
  4. Animal.call(this, name);
  5. }
  6. // 重写原型对象:把父类的共享方法继承下来
  7. Dog.prototype = Object.create(Animal.prototype)
  8. Dog.prototype.constructor = Dog;
  9. var d1 = new Dog('阿黄');
  10. var d2 = new Dog('阿红');

5.继承总结

5.1原型链继承

特点:重写子类的原型对象,父类原型对象上的属性和方法都会被子类继承

问题:在父类中定义的实例引用类型的属性,一旦被修改,其它的实例也会被修改

​ 当实例化子类的时候,不能传递参数到父类

5.2借用构造函数模式

特点:在子类构造函数内部间接调用(call(),apply(),bind())父类的构造函数

​ 原理:改变父类中的this指向

​ 优点:仅仅的是把父类中的实例属性当做子类的实例属性,并且还能传参

​ 缺点:父类中公有的方法不能被继承下来

5.3组合继承

特点:结合了原型链继承和借用构造函数继承的优点

​ 原型链继承:公有的方法能被继承下来

​ 借用构造函数:实例属性能被子类继承下来

缺点:调用了两次两次父类的构造函数

​ 1.实例化子类对象

​ 2.子类的构造函数内部(好)

5.4寄生组合式继承

  1. var b = Object.create(a);

将a对象作为b实例的原型对象

把子类的原型对象指向了 父类的原型对象

  1. Dog.prototype = Object.create(Animal.prototype)

[^开发过程中使用最广泛的一种继承模式]:

6.多重继承

多重继承:一个对象同时继承多个对象

定制Person对象

  1. function Person(){
  2. this.name = 'Person';
  3. }
  4. Person.prototype.sayName = function(){
  5. console.log(this.name);
  6. }

定制Parent

  1. function Parent(){
  2. this.age = 30;
  3. }
  4. Parent.prototype.sayAge = function(){
  5. console.log(this.age);
  6. }

继承Person的属性

  1. function Me(){
  2. Person.call(this);
  3. Parent.call(this);
  4. }

继承Person的方法

  1. Me.prototype = Object.create(Person.prototype);
  2. // 不能重写原型对象来实现 另一个对象的继承
  3. // Me.prototype = Object.create(Parent.prototype);
  4. // Object.assign(targetObj,copyObj)
  5. // 混入技术 Mixin
  6. Object.assign(Me.prototype,Parent.prototype);
  7. // 指定构造函数
  8. Me.prototype.constructor = Me;
  9. var me = new Me();

Object对象中相关方法介绍

1.Object对象本身的方法

Object的静态方法

1.1Object.keys(对象)

用法:参数是一个对象,返回是一个数组

  1. // Object.keys(对象)
  2. var arr = ['a','b','c'];
  3. console.log(Object.keys(arr));
  4. var obj = {
  5. 0: 'e',
  6. 1: 'f',
  7. 2 : 'j'
  8. }
  9. console.log(Object.keys(obj));

1.2getOwnPropertyNames(对象)

用法:返回不可枚举和枚举的属性名都能获取

Object.keys()返回可枚举的属性

接收一个对象作为参数,返回一个数组,包含了该对象自身的所有属性名

  1. var arr = ['a','b','c'];
  2. for(var key in arr){
  3. console.log(key);
  4. }
  5. //length不能够被遍历
  6. console.log(Object.getOwnPropertyNames(arr).length);
  7. var obj = {
  8. 0: 'e',
  9. 1: 'f',
  10. 2 : 'j'
  11. }
  12. console.log(Object.getOwnPropertyNames(obj).length);

1.3Object.getPrototypeOf()

用法:参数是该对象,返回该对象的原型,也是获取原型对象的标准方法

  1. function Fn(){};
  2. var f1 = new Fn();
  3. console.log(Object.getPrototypeOf(f1) === Fn.prototype);//true

介绍几种特殊对象的原型

空对象的原型是Object.prototype

  1. console.log(Object.getPrototypeOf({}) === Object.prototype);//true

Object.prototype 的原型是null

  1. console.log(Object.getPrototypeOf(Object.prototype) === null);//true

函数的原型是Function.prototype

  1. function f(){};
  2. console.log(Object.getPrototypeOf(f) === Function.prototype);

1.4Object.setPrototypeOf() 设置原型;Object.getPrototypeOf()获取原型

用法:接收两个参数,第一个参数是现有对象,第二个是原型对象

  1. var a = {};
  2. var b = {x : 1};
  3. Object.setPrototypeOf(a,b);
  4. console.log(a.x);//1
  5. console.log(Object.getPrototypeOf(a)); //a继承对象b,object
  1. function F(){
  2. this.foo = 'foo';
  3. }
  4. var f = Object.setPrototypeOf({},F.prototype); //var f = new F();与之等价
  5. F.call(f);//f.prototype.constructor = F;
  6. console.log(f);//输出原型对象F

1.5Object.create()

用法:一个实例对象生成另一个实例对象

接受一个对象作为参数,然后以它为原型,返回一个实例对象

  1. var A = {
  2. hello:function(){
  3. console.log('hello');
  4. }
  5. }
  6. var B = Object.create(A);
  7. console.log(Object.getPrototypeOf(B));
  8. B.hello();

2.Object实例方法介绍

2.1Object.prototype.valueOf()

用法:返回当前对象的值,默认情况返回对象本身

  1. var obj = new Object();
  2. //用自定义的Object.valueOf 覆盖 Object.prototype.valueOf
  3. obj.valueOf = function(){
  4. return 2;
  5. }
  6. console.log(obj.valueOf() === obj);//false
  7. console.log(1 + obj);//1[object Object]

2.2Object.prototype.toString()

用法:返回一个对象的字符串形式,默认返回类型字符串

  1. ar obj2 = {a: 1};
  2. obj2.toString = function(){
  3. return 'hello';
  4. }
  5. // 如果没有定制toString方法得到如下结果
  6. console.log(obj2.toString());//hello
  7. // 自定义了toString()方法
  8. console.log(obj2.toString() + ' world');//"hello world"
  9. var arr = [1,2,3];
  10. console.log(arr.toString());//1,2,3
  11. console.log('123'.toString());//123
  12. console.log((function(){
  13. return 123
  14. }).toString());//返回function(){return 123}
  15. console.log((new Date()).toString());//Fri Aug 28 2020 22:38:14 GMT+0800 (中国标准时间)

2.3Object.prototype.toLocaleString()

用法:当地地区标准

  1. console.log((new Date()).toLocaleString());//2020/8/28 下午10:42:01

2.4Object.prototype.isPrototypeOf()

用法:用来判断该对象是否是另一个对象的原型

  1. var o1 = {};
  2. var o2 = Object.create(o1);
  3. var o3 = Object.create(o2);
  4. console.log(o2.isPrototypeOf(o3));//true
  5. console.log(o1.isPrototypeOf(o3));//true
  6. console.log(o3);//{}
  7. console.log(Object.prototype.isPrototypeOf({}));//true
  8. console.log(Object.prototype.isPrototypeOf([]));//true
  9. console.log(Object.prototype.isPrototypeOf(Object.create(null)));//false
  10. console.log(Object.prototype.__proto__);//null

2.5hasOwnProperty()

用法:接收一个字符串作为参数,返回一个布尔值,表示该实例对象自身是否具有该属性,继承来的属性返回为false

  1. var obj = {
  2. a: 123
  3. }
  4. // obj.toString()
  5. console.log(obj.hasOwnProperty('a'));//true
  6. console.log(obj.hasOwnProperty('b'));//false
  7. console.log(obj.hasOwnProperty('toString'));//false

2.6Object.prototype.propertyIsEnumerable()

用法:判断某个属性是否可以遍历,只能判断实例对象本身的属性,对于继承来的属性和设置不可枚举的属性一律返回false

可枚举:可以遍历的属性

  1. var obj = {};
  2. obj.a = 123;
  3. console.log(obj.propertyIsEnumerable('a'));//true
  4. console.log(obj.propertyIsEnumerable('toString'));//false
  5. for(var key in obj){
  6. console.log(obj[key]);//123
  7. }
  8. var arr = [1,2,3];
  9. console.log(arr.propertyIsEnumerable('length'));//false

2.7getOwnPropertyDescriptor()

用法:属性描述对象:一个对象内部的数据结构

  1. var obj = {};
  2. obj.name = 'mjj';
  3. obj.name = 'alex';
  4. // console.log(delete obj.name);//与configurable,可配置属性相关
  5. // console.log(obj.propertyIsEnumerable('name'));//enumerable
  6. console.log(Object.getOwnPropertyDescriptor(obj,'name'));
  7. // console.log(obj.name);
  8. 输出的 name:
  9. {
  10. value: alex,
  11. writable:true,
  12. enumerable:true,
  13. configurable:true,
  14. set:undefined,
  15. get:undefined
  16. }

用法:可以获取属性描述对象.它的第一个是目标对象,第二个参数是一个字符串(目标对象的属性名)

  1. var arr = [1,2,3];
  2. arr.length = 5;
  3. console.log(arr.length);
  4. console.log(delete arr.length);
  5. // console.log(arr['length']);
  6. console.log(Object.getOwnPropertyDescriptor(arr,'0'));
  7. console.log(Object.getOwnPropertyDescriptor(arr,'length'));
  8. console.log(Object.getOwnPropertyDescriptor(arr,'toString'));//undefined 不能用于继承的属性 只能用于对象自身的属性

2.8Object.defineProperty()方法

用法:Object.defineProperty(属性所在的对象,属性名,属性描述对象),定义单个属性

  1. var obj = Object.defineProperty({},'name',{
  2. value:'mjj',
  3. writable:false, //可写性
  4. enumrable: true, //可遍历
  5. configurable: false //是否能被删除
  6. })
  7. console.log(obj.name);
  8. obj.name = 'alex';
  9. console.log(obj.name);
  10. /* for(var key in obj){
  11. console.log(obj[key]);
  12. } */
  13. delete obj.name;
  14. console.log(obj);

2.9Object.defineProperties()方法

用法:定义多个属性

  1. var obj = Object.defineProperties({},{
  2. p1:{
  3. value:123,
  4. enumerable:true
  5. },
  6. p2:{
  7. value:"mjj",
  8. enumerable:false
  9. },
  10. p3:{
  11. get:function(){
  12. return this.p1 + this.p2;
  13. },
  14. enumerable:true,
  15. configurable:true
  16. }
  17. })
  18. console.log(obj);
  19. console.log(obj.p1);
  20. // 一旦定义了取值函数get,就不能同时定义value属性,否则会报错
  21. /* var obj2 = Object.defineProperty({},'p',{
  22. value:'123',
  23. get:function(){
  24. return 456;
  25. }
  26. })
  27. console.log(obj2.p); */
  28. // 一旦定义了取值函数get,就不能同时定义writable
  29. var obj3 = Object.defineProperty({},'a',{
  30. get:function(){
  31. return 456;
  32. }
  33. })
  34. console.log(obj3.a);
  35. var obj4 = Object.defineProperty({},'foo',{});
  36. console.log(Object.getOwnPropertyDescriptor(obj4,'foo'));
  37. /* for(var key in obj4){
  38. console.log(obj4[key]);
  39. } */

2.10属性描述对象中的value和writable属性

  1. <script type="text/javascript">
  2. // "use strict";
  3. var obj = {};
  4. obj.p = 123;
  5. console.log(Object.getOwnPropertyDescriptor(obj,'p').value);
  6. Object.defineProperty(obj,'p',{value: 456});
  7. console.log(obj.p);
  8. // writable
  9. Object.defineProperty(obj,'p',{
  10. value: 890,
  11. writable:false
  12. });
  13. console.log(obj.p);
  14. obj.p = 100;
  15. console.log(obj.p);
  16. var pro = Object.defineProperty({},'foo',{
  17. value:'a',
  18. writable:false
  19. })
  20. var obj2 = Object.create(pro);
  21. Object.defineProperty(obj2,'foo',{
  22. value:'b'
  23. })
  24. console.log(obj2.foo);
  25. </script>

2.11enumrable属性用法

用法:如果一旦enumrable设置false,通常以下三个操作不会取到该属性

1.for…in;2.Object.keys();3.JSON.stringify()

  1. var obj = {};
  2. Object.defineProperty(obj, 'foo', {
  3. value: 123,
  4. enumrable:false
  5. })
  6. console.log(obj.foo);
  7. for(var key in obj){
  8. console.log(key);//不起任何作用
  9. }
  10. console.log(Object.keys(obj));//[]
  11. console.log(JSON.stringify(obj));//"{}"
  12. function A(){
  13. this.name = 'mjj';
  14. }
  15. function B(){
  16. A.call(this);
  17. }
  18. var b = new B();
  19. Object.defineProperty(b,'age',{
  20. value: 18,
  21. enumrable:false
  22. })
  23. console.log(b);

[^注意: for…in循环可以遍历继承来的属性]:

  1. for(var key in b){
  2. console.log(key);
  3. }
  4. // 可以获取继承来的属性
  5. // console.log(Object.keys(b));
  6. // getOwnPropertyNames 可以获取继承和不可遍历的属性
  7. console.log(Object.getOwnPropertyNames(b));

2.12configurable属性用法

用法:configurable 可配置性,决定是否我们可以修改属性描述对象

1.一旦设置configurable为false,属性描述对象 value,writable,enumrable,configurable都不能被修改

  1. var obj = Object.defineProperty({},'a',{
  2. value:1,
  3. writable:false,
  4. enumrable:false,
  5. configurable:false
  6. })
  7. // Cannot redefine property: a
  8. Object.defineProperty(obj,'a',{
  9. configurable: true
  10. })
  11. console.log(Object.getOwnPropertyDescriptor(obj,'a'));

2.注意:writable只有在false改为true的时候会静态失败,true改为false会允许的

  1. var obj2 = Object.defineProperty({},'p',{
  2. writable:true,
  3. configurable:false
  4. });
  5. Object.defineProperty(obj2,'p',{
  6. writable:false,
  7. configurable:false
  8. })
  9. obj2.p = 10;
  10. console.log(obj2);
  11. console.log(Object.getOwnPropertyDescriptor(obj2,'p'));

3.value属性 只要writable和 configurable有一个为true,就允许被修改

  1. var obj2 = Object.defineProperty({},'p',{
  2. value: 1,
  3. writable:false,
  4. configurable:true
  5. });
  6. Object.defineProperty(obj2,'p',{
  7. value:10
  8. })
  9. console.log(obj2);
  10. console.log(Object.getOwnPropertyDescriptor(obj2,'p'));

4.configurable一旦被配置了true,可以被删除,否则就不能被删除

  1. var obj = Object.defineProperties({},{
  2. a:{
  3. value: 1,
  4. configurable: true
  5. },
  6. b:{
  7. value: 2,
  8. configurable: false
  9. }
  10. });
  11. delete obj.a;
  12. delete obj.b;
  13. console.log(obj);

存取器

Object.defineProperty() get和set

  1. Object.defineProperty() //get和set
  2. var obj = Object.defineProperty({},'p',{
  3. get:function(){
  4. return 'getter';
  5. },
  6. set:function (value){
  7. // console.log('setter:' + value);
  8. return;
  9. }
  10. })
  11. console.log(obj.p);
  12. obj.p = 123;
  13. console.log(obj);
  14. var obj = {
  15. get p(){
  16. return 'getter';
  17. },
  18. set p(value){
  19. console.log('setter:' + value);
  20. }
  21. }
  22. console.log(obj.p);
  23. obj.p = 123;
  24. var obj = {
  25. n: 5,
  26. get a(){
  27. return this.n++;
  28. },
  29. set a(newValue){
  30. if(newValue > this.n){
  31. this.n = newValue;
  32. }else{
  33. throw new Error('新的值必须大于当前的值');
  34. }
  35. }
  36. }
  37. console.log(obj.a);
  38. console.log(obj.a);
  39. obj.a = 10;
  40. console.log(obj.a);
  41. obj.a = 3;

浅拷贝

  1. // 基本数据类型:按值传递
  2. var a = 1;
  3. var b = a;
  4. b = 200;
  5. console.log(b);
  6. console.log(a);
  7. // 引用数据类型:按引用地址传递
  8. var arr = [1,3,4];
  9. var newArr = arr;
  10. newArr.push(10);
  11. console.log(newArr);
  12. console.log(arr);
  13. // 拷贝: 浅拷贝 和 深拷贝
  14. // 操作拷贝之后的对象的某个属性不会影响原始对象中的属性,这种拷贝就称为叫深拷贝
  15. // 反之,有影响叫浅拷贝
  16. var obj = {
  17. name:'小马哥',
  18. age: 20,
  19. hobby:'eat',
  20. friend:{
  21. name:'alex',
  22. age:38
  23. }
  24. }
  25. function shadowCopy(toObj,fromObj){
  26. for(var key in fromObj){
  27. toObj[key] = fromObj[key];
  28. }
  29. // 来实现浅拷贝
  30. return toObj;
  31. }
  32. // 浅拷贝不是直接赋值,浅拷贝新建了一个对象,将原来对象的属性都一一的复制过来,复制的是值,而不是引用.浅拷贝的复制只复制了第一层的属性,并没有递归所有的值复制归来
  33. var newObj = shadowCopy({},obj);
  34. newObj.age = 30;
  35. newObj.friend.name = '阿黄';

深拷贝

深拷贝对目标对象的完全拷贝,不像浅拷贝那样只是复制了一层引用,就连值也复制过来

[^只要进行了深拷贝,它们老死不相往来,谁也不影响谁]:

  1. var obj = {
  2. name: '小马哥',
  3. age: 20,
  4. hobby: ['eat','songs'],
  5. friend: {
  6. name: 'alex',
  7. age: 38,
  8. hobby: '鸡汤',
  9. friend: {
  10. name: '阿黄',
  11. age: 10,
  12. hobby: 'play'
  13. }
  14. }
  15. }
  16. function deepCopy(to,from){
  17. // 遍历from对象的所有的属性,拷贝到to对象中
  18. for(var key in from){
  19. // 不遍历原型链上的属性
  20. if(from.hasOwnProperty(key)){
  21. /*如果值是对象并且有值,再遍历对象*/
  22. if(from[key] && typeof from[key] === 'object'){
  23. //区分是一般对象还是数组
  24. to[key] = from[key].constructor === Array ? [] : {};
  25. to[key] = deepCopy(to[key],from[key]);
  26. }else{
  27. // 如果不是,直接赋值
  28. to[key] = from[key];
  29. }
  30. }
  31. }
  32. return to;
  33. }
  34. var newObj = deepCopy({},obj);
  35. newObj.friend.name = '小红';
  36. console.log(newObj);
  37. console.log(obj);

ES6模块的基本实现

javascript代码

  1. <!-- 一个js文件就是一个模块 -->
  2. <script src="js/module1.js" type="text/javascript" charset="utf-8"></script>
  3. <script type="text/javascript">
  4. module1.m1();
  5. module1.m2();
  6. console.log(module1);
  7. </script>

module1.js

  1. // 业务逻辑
  2. // 1.字面量方式
  3. /* var module1 = new Object({
  4. count: 0,
  5. m1:function() {
  6. // ....
  7. },
  8. m2:function() {
  9. //....
  10. }
  11. })
  12. */
  13. // IIFE 立即执行函数
  14. var module1 = (function() {
  15. // count是一个私有的变量
  16. var count = 0;
  17. var m1 = function() {
  18. console.log('m1');
  19. //....
  20. };
  21. var m2 = function() {
  22. console.log('m2');
  23. //....
  24. }
  25. return {
  26. m1: m1,
  27. m2: m2
  28. }
  29. })();
  30. // 放大模式
  31. // 宽放大模式
  32. (function(mod){
  33. mod.m3 = function(){
  34. console.log('m3');
  35. }
  36. return mod;
  37. })(window.module1 || {});

命名空间避免全局变量污染

javascript代码

  1. <script src="js/namespace.js" type="text/javascript" charset="utf-8"></script>
  2. <script src="js/namespace_sub.js" type="text/javascript" charset="utf-8"></script>
  3. <script type="text/javascript">
  4. console.log(namespace);
  5. var p1 = new namespace.PersonInfo({
  6. name: 'mjj',
  7. gender: '男'
  8. });
  9. // console.log(p1);
  10. var helloStr = p1.getHello();
  11. console.log(helloStr);
  12. // namespace.personInfoUtil.show(p1);
  13. var c = new namespace.sub.Cat('闪电', '白色');
  14. c.sleep();
  15. console.log(c);
  16. </script>

namespace.js

  1. // 个人信息类
  2. // 姓名 性别
  3. var namespace = (function(namespace){
  4. // 声明了一个顶层的命名空间
  5. // 个人信息类:构造函数构建对象
  6. namespace.PersonInfo = function(obj){
  7. obj = obj || {};
  8. this.name = obj.name || '';
  9. this.gender = obj.gender || "?";
  10. }
  11. // 称谓方法
  12. namespace.PersonInfo.prototype.getAppellation = function(){
  13. var str = "";
  14. if(this.gender === '男'){
  15. str = '男士';
  16. }else{
  17. str = '女士';
  18. }
  19. return str;
  20. }
  21. // 欢迎的方法
  22. namespace.PersonInfo.prototype.getHello = function(){
  23. var s = "Hello " + this.name + this.getAppellation();
  24. return s;
  25. }
  26. // 个人信息工具类
  27. namespace.personInfoUtil = function(){
  28. return {
  29. // p形参是代指是哪个对象
  30. show:function(p){
  31. alert('姓名:'+ p.name+ ",性别:"+ p.gender);
  32. }
  33. }
  34. }()
  35. return namespace;
  36. })(window.namespace || {});

namespace_sub.js

  1. // 动物园
  2. namespace.sub = (function(sub){
  3. // 定义一个子的命名空间
  4. // 动物类
  5. // sub.Animal = {
  6. // createNew:function(){
  7. // var animal = {};
  8. // animal.sleep = function(){
  9. // alert('睡懒觉');
  10. // }
  11. // return animal;
  12. // }
  13. // }
  14. sub.Animal = function(name,color){
  15. this.name = name;
  16. this.color = color;
  17. }
  18. sub.Animal.prototype.sleep = function(){
  19. console.log('睡懒觉');
  20. }
  21. // 猫类
  22. sub.Cat = function(name,color){
  23. // 继承属性
  24. sub.Animal.call(this,name,color);
  25. }
  26. // 继承方法
  27. sub.Cat.prototype = Object.create(sub.Animal.prototype);
  28. sub.Cat.prototype.constructor = sub.Animal;
  29. return sub;
  30. })(window.namespace.sub || {});
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!