gpt4 book ai didi

Javascript instanceof 运算符混淆

转载 作者:行者123 更新时间:2023-11-30 09:20:24 26 4
gpt4 key购买 nike

我已经阅读了有关 Javascript 的 instanceof 运算符的内容,并想对其进行测试。我写了这段代码:

function first() {};
first.prototype.hello = function hello() {
console.log("hello");
}

var second = {};


second.prototype = Object.create(first.prototype);

console.log(second instanceof first); //should've output true

second.hello();

这并没有像我预期的那样工作。写这个片段时我的想法:

instanceof 将一个函数(在本例中为 first)作为其右手操作数,将一个对象作为其左手操作数。然后它检查给定函数的原型(prototype)是否出现在对象原型(prototype)链的任何部分。 first 是函数,hello 是添加到first 原型(prototype)的函数。 second 的原型(prototype)被分配了一个新对象,该对象具有指向 first.prototype 的原型(prototype)链接,因此当执行 second instanceof first 时,它找不到直接链接到 second 上的 first.prototype 对象,因此它遵循指向具有该链接的 second.prototype 的原型(prototype)链接。

当我在 Chrome 中运行时 this结果是:

false

Uncaught TypeError: second.hello is not a function
at main.js:13

你能帮我解决这个问题吗?

最佳答案

second's prototype is assigned a new object

不,这部分是错误的。您正在创建一个名为 “原型(prototype)” 的属性,但这并不意味着它是对象的实际原型(prototype)。

var second = {};
second.prototype = ...

相当于

var second = { "prototype": ... };

但它与继承无关。

几乎唯一使用名为 "prototype" 的属性的地方是在构造函数上(例如您的 first),即使那样它也不会用作函数本身的原型(prototype);它用作以后从 new ThatFunction() 创建的任何实例的原型(prototype)。

你能做的是

var second = new first;
// What this does:
// - gets the object from first.prototype
// - creates a new derived object, like Object.create(first.prototype)
// - calls first(), passing the new object as 'this',
// like first.call(Object.create(first.prototype))
// - assigns the object returned from first() to second
// (if first doesn't return an object, it automatically uses the new object created in step 2 instead)

或(大部分等同,但不会先调用)

var second = Object.create(first.prototype);

关于Javascript instanceof 运算符混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52159140/

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