进阶-原型

  • 设置对象的原型

    • Object.creacte( proto[, propertiesObject] )

      proto: 一个对象,作为新创建对象的原型
      propertiesObject: 对象属性定义
      var landRover = {
      name: "landRover",
      start: function () {
      console.log("%s start", this.logo);
      },
      run: function () {
      console.log("%s running", this.logo);
      },
      stop: function () {
      console.log("%s stop", this.logo);
      }
      }
      var landWind = Object.create(landRover);
      landWind.logo = "landWind";

      var landCruiser = Object.create(landRover);
      landCruiser.logo = "landCruiser";
      
      landWind.start();
      
    • 构造函数创建对象
      function Car(logo) {
        this.logo = logo || "unknow name";
      }
      Car.prototype = {
        name: "landRover",
        start: function () {
          console.log("%s start", this.logo);
        },
        run: function () {
          console.log("%s running", this.logo);
        },
        stop: function () {
          console.log("%s stop", this.logo);
        }
      }
      
      var landWind = new Car("landWind");
      var landCruiser = new Car("landCruiser");
      
      landWind.start();
      
  • 原型链

    //Car 构造函数
    function Car(logo) {
        this.logo = logo || "unknow name";
    }
    //设置Car的prototype属性
    Car.prototype = {
        start: function() {
            console.log("%s start", this.logo);
        },
        run: function() {
            console.log("%s running", this.logo);
        },
        stop: function() {
            console.log("%s stop", this.logo);
        }
    };
    
    //landRover构造函数
    function LanderRover(serialno) {
        this.serialNumber = serialno;
    }
    //设置LandRover的prototype属性
    LanderRover.prototype = new Car("landRover");
    
    //创建LandRover对象
    var landRover1 = new LanderRover(10000);
    var landRover2 = new LanderRover(10001);
    
进阶-原型_第1张图片
原型链.png

你可能感兴趣的:(进阶-原型)