在javascript中理解构造函数属性

时间:2013-04-25 03:28:56

标签: javascript

似乎我不理解constructor概念,所以,我写了一些代码来测试它。假设你有这样的代码:

var test=function(){...}

我知道constructor对象中有一个名为test.prototype的属性,指向test对象。

我的问题出现了:

此属性(constructor)是否仅属于原型对象?或者所有对象都具有constructor属性吗?

我又做了一次测试。代码如下:

            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 = Object.create(Shape);//inherit from the Shape instead of Shape.prototype
            Rectangle.constructor==Function//it is true.

我不知道Rectangle.constuctor来自哪里,或者它是否继承自Shape?感谢。

1 个答案:

答案 0 :(得分:2)

Object.create返回一个对象,其原型是您传递它的对象。

因此,由于Shape.constructorFunctionShapeFunction个对象),Rectangle会继承该内容。