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

 

posted @ 2016-10-08 11:23  peakleo  阅读(579)  评论(0编辑  收藏  举报