zoukankan      html  css  js  c++  java
  • 使用Object.create 克隆对象以及实现单继承

    var Plane = function () {
        this.blood = 100;
        this.attack = 1;
        this.defense = 1;
    };
    
    var plane = new Plane();
    plane.blood = 500;
    plane.attack = 5;
    plane.defense = 5;
    
    var clonePlane = Object.create(plane);
    console.log(clonePlane.blood);     //500
    console.log(clonePlane.attack );    // 5
    console.log(clonePlane.defense );// 5

    该方法属于ES5规范,如果浏览器环境不支持也可以自行实现,如下:

    Object.create = Object.create || function (obj) {
                var F = function () {};
                F.prototype = obj;
                return new F();
            }

    下面的例子演示了如何使用Object.create()来实现类式继承。这是一个单继承:

    //Shape - superclass
    function Shape() {
      this.x = 0;
      this.y = 0;
    }
    
    Shape.prototype.move = function(x, y) {
        this.x += x;
        this.y += y;
        console.info("Shape moved.");
    };
    
    // Rectangle - subclass
    function Rectangle() {
      Shape.call(this); //call super constructor.
    }
    
    Rectangle.prototype = Object.create(Shape.prototype);
    
    var rect = new Rectangle();
    
    rect instanceof Rectangle //true.
    rect instanceof Shape //true.
    
    rect.move(1, 1); //Outputs, "Shape moved."

     

  • 相关阅读:
    c语言寒假大作战02
    C语言寒假大作战01
    C语言I作业12
    C语言I博客作业11
    C语言I博客作业10
    C语言ll作业01
    C语言寒假大作战04
    C语言寒假大作战03
    C语言寒假大作战02
    C语言寒假大作战01
  • 原文地址:https://www.cnblogs.com/peakleo/p/6214143.html
Copyright © 2011-2022 走看看