理解javascript中的构造函数属性

Understand constructor property in javascript

本文关键字:构造函数 属性 javascript 理解      更新时间:2023-09-26

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

var test=function(){...}

我知道在test.prototype对象中有一个名为constructor的属性,它指向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 ?谢谢。

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

因此,由于Shape.constructorFunction (ShapeFunction对象),Rectangle继承了它。