面向对象

282 阅读2分钟

##面向对象:是一种编程思想(OOP) ##面向过程:也是一种编程思想 JS中的内置类:Array、String、Number、Boolean、Object、Function JS中的几种常见设计模式

  • 单例模式:其实就是一个对象,可以避免命名冲突的问题,可以用来封装一些工具函数、库。其中的对象名我们也称为命名空间
 var per1 = {
        name:'小明',
        age:10,
        sex:1,
        eat(){},
        play(){}
    }
  • 高级单例模式:也是一个对象;只是是由一个函数返回了一个单例
 function fn(){
        var name = '珠峰';
        var age = 10;
        function init(){
            console.log(name,age)
        }
        return {
            init
        }
    }
    var obj = fn();
    obj.init();
  • 工厂模式:封装一个函数
 function factory(name,age,sex){
        var obj = {
            name,age,sex,
            eat(){
                
            },
            play(){

            }
        }
        return obj;
    }
    var per11 = factory('小明',10,1);
  • 构造函数模式
 function Person(name,age,sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.eat = function(){}
        this.play = function(){}
        // return []
    }
     var per22 = new Person('zf',100,0);
    // per22 是 Person的 一个实例
    // new 执行函数的时候函数内部的this都是指向了一个堆内存;函数执行完成//之后; 又把this 返出去了
    // 若写了返回值 但是返回的是一个值类型;那么默认返回仍然是this;
    // 若返回值是个引用数据类型,则返回值就默认是这个引用数据类型了
    
    
     // es6 的箭头函数是不能通过new的方式执行
    // es6 创造类的方式 是通过 class创造的;
    var FN2 = ()=>{
        this.name = 111;
    }
    // console.log(new FN2);
    class FN3{
        constructor(name,age){
            this.name = name;
            this.age = age;
        }
    }
    var f3 = new FN3('小明',100);
    console.log(f3);

    var p1 = new Person('zf',10,1);
    var p2 = new Person('小明',20,0);
    console.log(p1,p2)
  • 原型模式:在构造函数的基础上加了一个 原型(prototype)的概念
 function Person(name='zf',age=10,sex=1){
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    console.log(Person.prototype)
    Person.prototype.eat = function(){
        console.log('吃');
    }
    Person.prototype.play = function(){
        console.log('玩');
    }
    Person.prototype.qqq = 123;
    var p1 = new Person();
    var p2 = new Person();
    p1.eat = function(){
        console.log(666)
    }
    console.log(p1,p2)
    
    //ES6
    class Fn{
        constructor(name,age){
            this.name = name;
            this.age = age;
        }
        eat(){

        }
        play(){

        }
    }
    // Fn  只能通过 new 的方式执行;
    var f = new Fn();
    console.log(f);