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."

     

  • 相关阅读:
    js 获得多个同name 的input输入框的值
    推荐系统
    异常检测
    降维——PCA主成分分析
    无监督学习——降维
    无监督学习——K-means聚类
    支持向量机——内核
    支持向量机背后的数学
    支持向量机——Large Margin Classifier
    支持向量机
  • 原文地址:https://www.cnblogs.com/peakleo/p/6214143.html
Copyright © 2011-2022 走看看