Skip to content

Latest commit

 

History

History
189 lines (125 loc) · 2.97 KB

面向对象.md

File metadata and controls

189 lines (125 loc) · 2.97 KB

OO (面向对象编程)

  • 面向对象的特性: 抽象 封装 多态 继承

继承的方式:

  • 原型链继承
function superType (){
  this.property= true
}
superType.ptototype.getSuperValue=function(){
  return this.proprerty 
}

 function subPerType (){
  this.subProperty= false
}
 subPerType.prototype = new superType()
 
 subPerType.prototype.getsubValue=funtion(){
  return this.subProperty
 }
 
 var instance = new subPerType()
  
  console.log(instance.getSuperValue()) // true
  • 借用构造函数
function superType (){
  this.color= ['red',bule','green']
}

function subPerType (){
 superType.call(this)
}

 var instance = new superType()
 
 instance.color.push('black')
 
 consoel.log(instance.color) //['red',bule','green','black']
 
 var instance1 = new subPerType()
 
 consoel.log(instance1.color) //['red',bule','green']
  • 组合继承
function superType (name){
  this.name= name
}
superType.ptototype.sayname=function(){
  console.log(this.name)
}

function subPerType (name.age){
  superType.call(this,name)
  this.age=age
}

subPerType.prototype = new superType()

subPerType.prototype.constructor = subPerType

subPerType.prototype.sayAge = funtion (){
  console.log(this.age)

}
  • 原型式继承
function object1 (o){
   function F(){}
   F.prototype= o 
    return new F()
}
var person =  {name:'chris'}

var personInstance = object(person)
  • 寄生式继承
function creatAnother(original) {
   var clone = object(original)
   clone.sayHi= function (){
    console.log(hi)
   }
   return clone
}
  • 寄生继承组合式
function inheritprototype (subType,superType){
   var prototype = object1(superType.prototype)
    prototype.constructor= subType
    subType.prototype=prototype 
}


function superType (name){
  this.name = name
}
superType.prototype.sayName = function() {
  console.log(this.name)
}

function subType (name,age){

   superType.call(this,name)
   this.age  = age 
}

inheritprototype(subType,superType) //  主要继承位置 很重要 

subType.prototype.sayAge = function (){
  console.log(this.age )
 }

多态(相同的额操作不同的表现)

多态背后的思想是将 ”做什么“和” 谁去做以及怎样去做分开

\\  普通的写法
var makeSound = function(animal) {
    if(animal instanceof Duck) {
        console.log('嘎嘎嘎');
    } else if (animal instanceof Chicken) {
        console.log('咯咯咯');
    }
}
var Duck = function(){}
var Chiken = function() {};
makeSound(new Chicken());
makeSound(new Duck());

// 多态的写法

var makeSound = function(animal) {
    animal.sound();
}

var Duck = function(){}
Duck.prototype.sound = function() {
    console.log('嘎嘎嘎')
}
var Chiken = function() {};
Chiken.prototype.sound = function() {
    console.log('咯咯咯')
}

makeSound(new Chicken());
makeSound(new Duck());