javascript属性值函数未继承

时间:2013-12-26 21:09:11

标签: javascript

值“x,y,width和height”由ShapeFactory创建的对象“SquareFactory”创建的对象继承,但是函数right()不会被继承。我假设该行

 square.protoype = ShapeFactory();

为要搜索的属性创建链接。但这似乎并没有发生。我错过了原型的一些东西。我阅读了How does JavaScript .prototype work?,但无法通过我目前对原型的理解找到错误。

function ShapeFactory() {
    return {
    x: 0,
    y: 0,
    width: 0,
    height: 0,      
    right: function () {
        return this.x + this.width;
    }
    };
}
function SquareFactory() {
    var square = {
    insideBoundary: function (x, y) { // this function works
        return (x > this.x && x < (this.x + this.width)
            && y > this.y && y < (this.y + this.height));
    },
    print_info: function () { // this function throws error
        console.log(this.x + " " + this.y + " "
            + this.width + " " + this.height
            + this.right() + " " + this.bottom()); // error accessing right() fn
    }
    };
    square.protoype = ShapeFactory();
    return square;
}

1 个答案:

答案 0 :(得分:1)

这是一个有效的例子:

function ShapeFactory() {
    this.x = 0;
    this.y = 0;
    this.width = 0;
    this.height = 0;
}

ShapeFactory.prototype.right = function () {
    return this.x + this.width;
};

function SquareFactory() {
    ShapeFactory.call(this);
}

SquareFactory.prototype = Object.create(ShapeFactory.prototype);

SquareFactory.prototype.insideBoundary = function (x, y) {
    return (x > this.x && x < (this.x + this.width) && y > this.y && y < (this.y + this.height));
};

SquareFactory.prototype.print_info = function () {
    console.log(this.x + " " + this.y + " " + this.width + " " + this.height + this.right());
};

var shapeFactory = new ShapeFactory();
var squareFactory = new SquareFactory();

console.log(ShapeFactory.prototype.right === SquareFactory.prototype.right); // ShapeFactory and SquareFactory are sharing the same right function

console.log(squareFactory instanceof SquareFactory); // squareFactory is a SquareFactory
console.log(squareFactory instanceof ShapeFactory); // squareFactory is also a ShapeFactory
console.log(shapeFactory instanceof SquareFactory); // shapeFactory is not a SquareFactory
console.log(shapeFactory instanceof ShapeFactory); // shapeFactory is a ShapeFactory

squareFactory.print_info();