gpt4 book ai didi

javascript - 为什么要设置原型(prototype)构造函数?

转载 作者:IT老高 更新时间:2023-10-28 13:11:40 25 4
gpt4 key购买 nike

section about inheritance in the MDN article Introduction to Object Oriented Javascript ,我注意到他们设置了prototype.constructor:

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;

这有什么重要目的吗?可以省略吗?

最佳答案

它并不总是必要的,但它确实有它的用途。假设我们想在基础 Person 类上创建一个复制方法。像这样:

// define the Person Class  
function Person(name) {
this.name = name;
}

Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new this.constructor(this.name);
};

// define the Student class
function Student(name) {
Person.call(this, name);
}

// inherit Person
Student.prototype = Object.create(Person.prototype);

现在,当我们创建一个新的 Student 并复制它时会发生什么?

var student1 = new Student("trinth");  
console.log(student1.copy() instanceof Student); // => false

副本不是 Student 的实例。这是因为(没有显式检查),我们无法从“基”类返回 Student 副本。我们只能返回一个Person。但是,如果我们重置了构造函数:

// correct the constructor pointer because it points to Person  
Student.prototype.constructor = Student;

...然后一切都按预期进行:

var student1 = new Student("trinth");  
console.log(student1.copy() instanceof Student); // => true

关于javascript - 为什么要设置原型(prototype)构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8453887/

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