[英]Object.prototype does not make right inheriting
I have a code that based on class inheritance. 我有一个基于类继承的代码。 The Rabbit constructor inherit methods from Animal prototype and then create an object rabbit with Animal methods .
从动物原型 兔构造继承方法,然后创建具有动物方法的对象 的兔子 。
I can not understand - why the Rabbit constructor does not want inherit the Animal.prototype.name method. 我不明白-为什么Rabbit构造函数不想继承Animal.prototype.name方法。 It's exactly as an Animal.prototype.run, but it does not work...
它与Animal.prototype.run完全一样,但是不起作用...
function Animal(name) { this.name = name; this.speed = 0; } Animal.prototype.run = function(speed) { this.speed += speed; console.log( this.name + ' run, speed ' + this.speed ); }; Animal.prototype.name = function(name) { this.name = name; console.log( 'Rabbit name ' + this.name ); }; Animal.prototype.stop = function() { this.speed = 0; console.log( this.name + ' stay' ); }; function Rabbit(name) { Animal.apply(this, arguments); } Rabbit.prototype = Object.create(Animal.prototype); Rabbit.prototype.constructor = Rabbit; Rabbit.prototype.jump = function() { this.speed++; console.log( this.name + ' jump' ); }; var rabbit = new Rabbit('Rabbit'); rabbit.name(); // Error, but it must display "Rabbit" rabbit.run(); // works fine rabbit.jump(); // works fine
You have object field "name" and function "name". 您具有对象字段“名称”和功能“名称”。 Field is overriding the function.
字段覆盖功能。
Solution rather simple - rename one or another. 解决方案相当简单-重命名一个或另一个。
.name
is not a method, in the constructor it gets assigned the argument string. .name
不是方法,在构造函数中,它被分配了参数字符串。 This own property shadows the inherited method. 这个自己的属性遮盖了继承的方法。 Calling the string will produce the error.
调用字符串将产生错误。
Change it to 更改为
Animal.prototype.setName = function(name) {
this.name = name;
console.log( 'Rabbit name ' + this.name );
};
…
console.log(rabbit.name); // displays "Rabbit"
rabbit.setName("Roger"); // displays "Rabbit name Roger"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.