Javascript 原型比较未给出预期结果

Javascript prototypes comparision giving not expected results

我试图在 This Link

中理解 javascript 原型继承

然后开始尝试以下关于继承原型分配的实验,

function Person() {}
Person.prototype.dance = function() {};

function Employee() {}

function Student() {}

Employee.prototype = new Person();
Student.prototype = new Person();

emp = new Employee();
stu = new Student();

console.log("Person Object Equal : " + (new Person() == new Person()));
console.log("Emp and Stu Prototype Equal : " + (Employee.prototype == Student.prototype));
console.log("Emp and Stu Object Prototype Equal : " + (emp.prototype == stu.prototype));
console.log("Emp and Stu Object Equal : " + (emp == stu));

如果 Class 变量 Employee.prototype==Student.prototype 为 returning false, 那么对象变量 emp.prototype==stu.prototype 如何 return 为真?

我在想 emp.prototype==stu.prototype 也会 return false 因为它们将指向与其 class 函数相同的原型。

有人可以解释一下这背后的逻辑吗? 也许我在这里漏掉了一些要点..?

您可以复制上面的代码和运行在上面提供的Same Link中进行测试。

我明白了,你真正想要的是:

function Person() {}
Person.prototype.dance = function() {};

function Employee() {}

function Student() {}

// Employee.prototype = new Person();
// Student.prototype = new Person();

const person = new Person();
Employee.prototype = person;
Student.prototype = person;


const emp = new Employee();
const stu = new Student();

console.log("Person Object Equal : " + (new Person() === new Person()));
console.log("Emp and Stu Prototype Equal : " + (Employee.prototype === Student.prototype));
console.log("Emp and Stu Object Prototype Equal : " + (emp.prototype === stu.prototype));
console.log("Emp and Stu Object Equal : " + (emp === stu));

第三次检查 return 为真的原因很简单,就是 stu.prototypeemp.prototype 都未定义。 .prototype是构造函数上存在的属性;它不存在于 newing 该构造函数创建的对象上。

emp 确实有一个 emp.__proto__ 属性,但这已被弃用,您不应直接访问它。 emp.__proto__ === Employee.prototype 将 return 为真。访问原型的未弃用方法是 Object.getPrototypeOf(emp),尽管即使那样你也很少有理由使用。