gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:22:54 27 4
gpt4 key购买 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

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

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

function Hero(){ } 

var h1 = new Hero();

h1.constructor

Output >>> function Hero()

概念上的区别是什么?

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

最佳答案

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() where 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]]: true, [[Enumerable]]: false, [[Configurable]]: true}, and false.
  • Call the [[DefineOwnProperty]] internal method of F with arguments "prototype", Property Descriptor {[[Value]]: proto, { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false}, and false.
  • ...

示例:

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

因此,当您用另一个对象覆盖 F.prototype 时,您会丢失 constructor 属性。

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

  1. ninja2 没有自己的 constructor 属性。
  2. ninja2 继承自 ninja,它没有自己的 constructor 属性。
  3. ninja 继承自 Object.prototype,它有一个自己的 constructor 属性,设置为 Object。<

要解决此问题,您可以

  • 恢复F.prototype中的构造函数:

    function F(){}
    F.prototype = ninja;
    F.prototype.constructor = F;
  • ninja中包含构造函数:

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

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

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

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