您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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
javascript 2022/1/1 18:17:42 有416人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶