原型以及继承开发模式[JavaScript_010]

2019-03-17  本文已影响0人  六亲不认的步伐

原型


Car.prototype.speed =50;
    function Car()
    {
    };
var car1 = new Car();
var car2 = new Car();
//输出的car1.speed和car2.speed的值为50,原因是从公共对象(原型)继承
function Car()
{
}
Car.prototype.constructor = Person();//对原型的构造函数查看内容进行篡改
function Person()
{
}
var myCar = new Car();
console.log(myCar.constructor )//会输出篡改后的Person()
    function Animal(){
          var this = {
                __proto__ : Animal.prototype
          }; 
    }
    Animal.prototype.name = "Alice";
    function Animal(){          
    }
    var cat(){
          name:"Sunny"
    }
    var cat = new Animal();
    cat.__proto__ = cat;//__proto__用于存储原型,此处被修改
    console.log(cat.name);//输出为Sunny,并非Alice
    Animal.prototype.name = "A";
    function Animal(){          
    }
    var cat = new Animal();
    //Animal.prototype.name = "C" (改属性)
    Animal.prototype{//(改空间)
          name:"B"
    }
    //输出的cat.prototype.name 为A
    //1.若注释的取消则为C
    //2.若B在对象之前修改才输出B
输出A的原因是,Animal.prototype换了存储内容,但是__proto__还是原来的继承,为A

Object.create()

    Animal.prototype.name = "A";
    function Animal(){          
    }
    var animal  = Object.Create(Animal);   

重写方法(toString)

    Animal.prototype.toString=function (){       
        console.log('A');   
    }
    var animal  = Object.Create(Animal);     
    animal.toString();//会输出A
    var animal  = Object.Create(Animal);     
    animal.toString = function(){
        return 'A';
    }
    document.write(animal);//隐式调用了toString方法

Call/apply

    function Person(name){//类似与工厂
    this.name = name;
    }
    var person =new Person('test');
    var obj ={};
    Person.call(obj,'obj_test');//将this 从Person转为obj,类似借用工厂
    person.name ;//会输出obj_test
    function Person(name,tel){//类似与工厂
    this.name = name;
    this.tel =tel;
    }
    function Student(name,age,tel){
        Person.call(this,name,tel);//使用工厂(继承父类变量,用自己进行实现)
        Person.apply(this,[name,tel]);//与call等价
        this.age = age;
    }
    var student=new Student('test01',"test02","test03");

继承


  1. 传统模式(原型链)
  1. 借用构造函数
  1. 共享原型(inherit,extend)
  1. 圣杯模式
    function inherit(target,origin){//类似与工厂
      function Middle(){};//中间类
      Middle.prototype = origin.prototype;
      target.prototype = new Middle();
      target.constuctor = target;
      target.prototype.uber = origin.prototype;//存储真正的 父类
    }
    function Father(){     
    }
    function Son(){     
    }
    inherit(Son,Father);//必须在new之前
    var son=new Son();
    function inherit(target,origin){
      var Middle =  function (){};//闭包起到私有化作用
      return function(target,origin){
          Middle.prototype = origin.prototype;
          target.prototype = new Middle();
          target.constuctor = target;
          target.prototype.uber = origin.prototype;
      }
    }
    function Father(){     
    }
    function Son(){     
    }
    inherit(Son,Father);//必须在new之前
    var son=new Son();
上一篇 下一篇

猜你喜欢

热点阅读