JavaScript 在子类中设置构造函数?

标签 javascript inheritance prototypal-inheritance

下面是一个简单的 JavaScript 继承示例。该线路的目的是什么 从下面?

Dog.prototype.constructor = Dog;

如果我取消注释或注释掉,代码似乎会给出相同的输出。

function Animal(age){
    this.age = age;
    console.log("Animal constructor called")
}
Animal.prototype.walk = function(){
     console.log("Animal with age " + this.age + " walked"); 
}

function Dog(color, age){
    this.color = color;
    Animal.call(this, age)
    console.log("Dog constructor called")
}

Dog.prototype = new Animal();      
//Dog.prototype.constructor = Dog;

dog = new Dog("white", 10);
console.log("Age: " + dog.age +  " Color: " + dog.color );

最佳答案

定义函数时,会自动创建 prototype 属性:

function Animal(age){
    this.age = age;
    console.log("Animal constructor called")
}

Animal.prototype.walk = function(){
     console.log("Animal with age " + this.age + " walked"); 
}

了解了构造函数,引用原型(prototype)对象就很容易了:Animal.prototype

prototype对象端来看,它有一个constructor属性来访问原始函数:Animal.prototype.constructor === Animal 。这对于从实例确定它的原始类是什么很有用:

var lion = new Animal();
console.log(lion.constructor === Animal) // prints "true"
console.log(lion.__proto__.constructor === Animal) // prints "true"
<小时/>

如果是继承,则需要手动设置构造函数:

Dog.prototype = new Animal();     
console.log(Dog.prototype.constructor) // prints "function Animal(){}"
Dog.prototype.constructor = Dog;       // setup manually the constructor to Dog
console.log(Dog.prototype.constructor) // prints "function Dog(){}"

为了稍后验证它的正确性:

var dog = new Dog("white", 10);

console.log(dog.constructor === Animal)           // prints "false"
console.log(dog.__proto__.constructor === Animal) // prints "false"
console.log(dog.constructor === Dog)              // prints "true"
console.log(dog.__proto__.constructor === Dog)    // prints "true"
<小时/>

简而言之,如果您想使用构造函数来验证哪个类具有特定实例,则应该修复构造函数。

关于JavaScript 在子类中设置构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36093325/

相关文章:

javascript - 仅当 td 在特定 html 标记后不包含内容时隐藏 tr

javascript - 如何在不将用户发送到页面顶部的情况下触发 javascript playsound 事件 onclick?

c++ - 用模板方法重写虚方法

javascript - instanceof 检查在不设置构造函数的情况下对子类起作用

javascript继承模式比较

javascript - 使用 minicart.js 显示购物车中的商品数量

javascript - 使用在两个(或更多)缓冲区 block 之间拆分的大型 JSON 的最佳方法是什么

java - 映射通过引用具有继承的未知目标实体属性

c++ - 使用子类操作类

javascript - 使用Object.create()实现多重继承