美文网首页
进阶-原型

进阶-原型

作者: zz张哲 | 来源:发表于2016-09-28 18:21 被阅读0次
    • 设置对象的原型

      • 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);
      
    原型链.png

    相关文章

      网友评论

          本文标题:进阶-原型

          本文链接:https://www.haomeiwen.com/subject/jxzhyttx.html