11-19面向对象

1.使用typeof运算符确定对象的基本类型

  (number,string,function,undefined,object),

    如果typeof运算符返回object,

    再用instanceof和constructor来确定该对象是否属于某个具体类型

      var arr=[];
        console.log(typeof arr);//object
        console.log(arr instanceof Array);//true
        console.log(arr.constructor);//array

2.JavaScript 自定义对象

  创建新对象有多种不同的方法:

   1. 直接给对象扩充属性和方法 、对象字面量

   2. 工厂方式

   3. 构造函数方式  

  4. 原型(prototype)方式

  5. 混合方式(构造函数和原型) .........

// 1.直接给对象扩充属性和方法
        var cat1={};
        cat1.name='小猫';
        cat1.color='white';
        cat1.skill=function(){
            alert('喵喵');
        }
        alert(cat1.name);//小猫
        cat1.skill();//喵喵
        // 2.对象字面量
        var cat2={
            name:'小黑',
            color:'black',
            skill:function(){
                alert('111');
            }
        };
        console.log(cat2.name);//小黑
        //3.工厂方式
        function cat4(n,c){
            var cat={};
            cat.name=n;
            cat.color=c;
            cat.skill=function(){
                alert('lalal');
            }
            return cat;
        }
        var cat5=cat4('小红','red');
        cat5.skill();//lalal
        //4.构造函数
        function Cat(n,c){
            this.name=n;
            this.color=c;
            this.skill=function(){
                alert('构造函数');
            }
        }
        var cat6=new Cat('小兰','blue');
        cat6.skill();//构造函数
        //5.原型(prototype)方式
        function Cat10(){};
        Cat10.prototype.name='小绿';
        Cat10.prototype.color='green';
        Cat10.prototype.skill=function(){
            alert('原型方法');
        }
        var cat11=new Cat10();
        cat11.skill();//原型方法
        function Cath(n,c){
            this.name=n;
            this.color=c;
            this.food='猫粮'
        }
        Cath.prototype.skill=function(){
            alert('混合方式');
        }
        var cat12=new Cath('小王','black');
        cat12.skill();//混合方法

(1)构造函数

    当任意一个普通函数用于创建一类对象时,它就被称作 构造函数 或 构造器 (constructor)

    构造函数的作用就是初始化一个新创建的对象,并在使用对象前设置对象的属性和方法。

     通常是利用无敌的this,在函数内部对 this 添加属性和方法,因为this就表示当前运行时的对象,将构造函数this的作用域指向新对象,将当前运行对象的属性和方法都赋给新对象,这样的对象模式称为构造函数模式

   javascript的方法可以分为三类:

     1. 对象方法 2. 类方法 3. 原型方法

    每个函数对象都有一个prototype(原型)属性

    prototype 属性可向对象添加属性和方法

    Javascript中对象的prototype属性的解释是: 返回对象类型原型的引用

(2)prototype原型

  所有创建在prototype上的属性和方法

  都将被所有对象实例分享(继承)

  指针指向的就是prototype对象

  prototype有一个注意点,如果是方法,可以共用内存,如果是一个属性,还是会新开内存的。   混合方式创建对象: 构造函数和原型混合使用,构造函数定义对象的属性,原型(prototype)定义对象的方法,这样就可以做到属性私有,方法共享

原文地址:https://www.cnblogs.com/SunShineM/p/6080711.html