下面是一个简单的 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/