cuốn sách gpt4 ai đã làm

JavaScript - 意外/奇怪的构造函数

In lại Tác giả: Walker 123 更新时间:2023-11-28 19:22:54 29 4
mua khóa gpt4 Nike

var ninja = {
name: 'Ninja',
say: function () {
return 'I am a ' + this.name;
}
};

function F(){
}

F.prototype = ninja;

var ninja2 = new F();

ninja2.name;

Output >>> "Ninja"

ninja2.constructor === F

Output >>> false

ninja2.constructor

Output >>> function Object()

ninja2.__proto__ === ninja

Output >>> true

在这个例子中,为什么FKHÔNGninja2的构造函数
(正如人们所期望的那样)?!

我希望如此,因为...下一个示例将打印 Hero.

function Hero(){ } 

var h1 = new Hero();

h1.constructor

Output >>> function Hero()

概念上的区别是什么?

我认为这与我在第一个示例中显式设置 F.prototype = ninja; 的事实有关。但它与此有什么关系呢?我对此很困惑。 F KHÔNG ninja2 的构造函数吗?毕竟new F()是用来创建ninja2的?

câu trả lời hay nhất

constructor 属性没有什么魔力,它只是创建函数对象时自动添加的一个属性:

13.2 Creating Function Objects

  • Create a new native ECMAScript object and let F be that object.
  • ...
  • Let proto be the result of creating a new object as would be constructed by the expression new Object() Ở đâu Object is the standard built-in constructor with that name.
  • Call the [[DefineOwnProperty]] internal method of proto with arguments "constructor", Property Descriptor {[[Value]]: F, { [[Writable]]: ĐÚNG VẬY, [[Enumerable]]: SAI, [[Configurable]]: ĐÚNG VẬY}, and SAI.
  • Call the [[DefineOwnProperty]] internal method of F with arguments "prototype", Property Descriptor {[[Value]]: proto, { [[Writable]]: ĐÚNG VẬY, [[Enumerable]]: SAI, [[Configurable]]: SAI}, and SAI.
  • ...

Ví dụ:

function F(){}
F.prototype.constructor; // F

因此,当您用另一个对象覆盖 F.prototype 时,您会丢失 constructor tài sản.

然后,当您使用ninja2.constructor时,您会得到Object,因为:

  1. ninja2 没有自己的 constructor tài sản.
  2. ninja2 Kế thừa từ ninja,它没有自己的 constructor tài sản.
  3. ninja Kế thừa từ Object.prototype,它有一个自己的 constructor 属性,设置为 Object。<

要解决此问题,您可以

  • 恢复F.prototypeTRONG构造函数:

    function F(){}
    F.prototype = ninja;
    F.prototype.constructor = F;
  • hiện hữuninja中包含构造函数:

    var ninja = {
    constructor: F, /* ... */
    };
  • 将所需的属性添加到F.prototype,而不是用另一个对象替换它:

    Object.assign(F.prototype, ninja); /* Requires ECMAScript 6 */

关于JavaScript - 意外/奇怪的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28466352/

29 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress