gpt4 book ai didi

javascript - 了解 JavaScript 中的构造函数属性

转载 作者:行者123 更新时间:2023-12-02 18:47:33 25 4
gpt4 key购买 nike

看来我不理解构造函数的概念,所以,我写了一些代码来测试它。假设您有这样的代码:

var test=function(){...}

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

这是我的问题:

此属性(构造函数)仅属于原型(prototype)对象吗?或者所有对象都有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返回一个对象,其原型(prototype)是您传递给它的对象。

因此,自 Shape.constructorFunction ( ShapeFunction 对象), Rectangle继承了这一点。

关于javascript - 了解 JavaScript 中的构造函数属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16205876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com