我修改了JavaScript的构造函数是什么意思?

时间:2015-02-21 07:01:03

标签: javascript prototype prototypal-inheritance

我是JavaScript的新手,我试图了解原型和构造函数。我编写了一些小代码,但我无法从中推断出任何东西。

function shape() {

    this.name = "shape";

    this.toString = function() {
        return this.name;
    }
}

function Rectangle(w, h) {

    this.name = "Rectangle";
    this.width = w;
    this.height = h;

    this.area = function() {
        return (2 * (this.width + this.height));
    }
}


function Square(side) {
    this.name = "Square";

    this.area = function() {
        return (side * side);
    }
}


rect = new Rectangle(10, 20);
sq = new Square(100);

rect.constructor //gives Rectangle(w, h)

这意味着rect对象是从Rectangle()构造函数

创建的实例

但有趣的是,当我写下以后的行

rect.constructor=Square;
rect.prototype=shape;
rect.constructor //gives Square(side)
  1. 我已将原型引用为shape,意味着我已经继承了shape

    的属性
    var hybrid=new rect.constructor();
    
    hybrid.name //gives "Square"
    
  2. 现在从rect对象我可以用Square()构造函数(模板)创建一个对象,也可以通过原型访问形状的属性,也可以访问自己的矩形属性。但我不明白构造函数部分

    为什么java Script允许这样强大的语法。是否有任何实际优势,如果我在上述陈述中的任何地方出错,也可以纠正我

0 个答案:

没有答案