技术干货让前端飞

面向对象

2017-01-07  本文已影响0人  六月太阳花
  1. 对象:某一个具体的东西

  2. 类:类别,一类东西

  3. 变量和属性
    变量就是属性,属性就是变量,只是叫法不同
    变量是自由的
    属性是属于某一对象的

  4. 函数和方法
    函数就是方法,方法就是函数,只是叫法不同
    函数是自由的
    方法是属于某个对象的

  5. 构造函数
    功能:用来创建对象的
    规范:首字母大写

  6. 函数当做对象
    new以后函数当做对象
    new Person();
    属性:加到构造函数里面
    方法:加给原型prototype

  7. this 这个方法属于赋给谁,那么谁就是这个this

  8. 检测
    基本数据类型 typeof number string boolean undefined object function
    检测复合类型 instanceof
    检测构造函数 constructor
    eg:

    Function instanceof Object      true
    Object instanceof Function      true
    Object instanceof Object        true
    Function instanceof Function    true

    var arr=new Array();
    arr instanceof Array        true
    Array instanceof Object     true
    arr instanceof Function     false

    Object.prototype.a=5;
    var a=12; 
    alert(a.a);              //5 
    alert(a instanceof Object);         //false 
    Object.prototype.a=5;
    var a=new Number(); 
    alert(a.a);               //5 
    alert(a instanceof Object);         //true
  1. 面向对象的特性:
    封装 抽取核心封装
    继承 子级继承父级,父级有的子级就有,子级有的父级不一定有,父级做出改变,子级跟着改变。
    多态 多重继承,多种状态

  2. 继承
    属性继承:
    fn.call(this,参数1,参数2);
    fn.apply(this,[参数1,参数2]);
    fn.apply(this,arguments);

    方法继承: 
    
    Worker.prototype=Person.prototype
    有引用问题 
    
    for(var name in Person.prototype){
        Worker.prototype[name]=Person.prototype[name];
    }
    不属于父级 
    
     Worker.prototype=new Person();
     构造函数是Person
    
    Worker.prototype=new Person();
    Worker.prototype.constructor=Worker;
    

继承eg:

function Person(name,age){
      this.name=name;
      this.age=age;
};
Person.prototype.showName=function (){
    return this.name;
};
Person.prototype.showAge=function (){
    return this.age;
}; 
function Worker(name,age,job){
    Person.apply(this,arguments);
    this.job=job;
} 
Worker.prototype=new Person();
Worker.prototype.constructor=Worker;
Worker.prototype.showJob=function (){
    return this.job;
}; 
var p1=new Person('小明',16);
var w1=new Worker('小红',18,'扫地的');

  
alert(p1.showJob);                  //undefined
alert(w1 instanceof Person);        //true 
alert(w1.constructor);           //构造函数是Worker

加方法的另一种写法

    function Person(name,age){
        this.name=name;
        this.age=age;
    } 
    Person.prototype={
        constructor:Person,
        showName:function (){
            return this.name;
        }
    };

单列模式

    简单,不能继承 
    var Person={
        name:'Abel',
        age:18,
        showName:function (){},
        showAge:function (){}
    };
上一篇 下一篇

猜你喜欢

热点阅读