gpt4 book ai didi

javascript - Javascript 中的 isPrototypeOf

转载 作者:数据小太阳 更新时间:2023-10-29 04:05:14 25 4
gpt4 key购买 nike

我是 JavaScript 的初学者,正在学习 JavaScript 原型(prototype)
根据文章here

创建原型(prototype)
创建对象原型(prototype)的标准方法是使用对象构造函数:

function person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}

通过构造函数,您可以使用 new 关键字从同一原型(prototype)创建新对象:

var myFather = new person("John", "Doe", 50, "blue");
var myMother = new person("Sally", "Rally", 48, "green");

构造函数是您的 person 对象的原型(prototype)。
我发现自己对上面的粗线感到困惑,我认为这是绝对错误的。

原因:

alert(person.isPrototypeOf(myFather));  // false

我这么说对吗,因为我相信这条线:

The ‘prototype’ property points to the object that will be assigned as the prototype of instances created with that function when using ‘new’.

最佳答案

我同意术语不正确。

构造函数有一个prototype属性,它定义了原型(prototype)链中的属性和方法;但它本身不是对象的原型(prototype),它是构造函数。

isPrototypeOf不是在构造函数本身上调用,而是在构造函数的原型(prototype)属性上调用。

alert(person.prototype.isPrototypeOf(myFather)); // true

myFather 将是 instanceof person,您可以使用以下行对其进行测试。

alert(myFather instanceof person); // true

关于javascript - Javascript 中的 isPrototypeOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27890392/

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