栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript为什么需要设置原型构造函数?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript为什么需要设置原型构造函数?

并非总是必要的,但是它确实有其用途。假设我们想在基

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/442049.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号