Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript中继承的正确语法_Javascript - Fatal编程技术网

javascript中继承的正确语法

javascript中继承的正确语法,javascript,Javascript,非常琐碎的问题 我试图理解javascript中的继承 function Animal() { this.eats = true; } function Rabbit() { this.jumps = true; } //Rabbit is-a Animal Rabbit.prototype = Animal; //I'm assuming this does not inherit alert(Rabbit.prototype.eats); // returns undefined

非常琐碎的问题

我试图理解javascript中的继承

function Animal() {
  this.eats = true;
}
function Rabbit() {
  this.jumps = true;
}
//Rabbit is-a Animal
Rabbit.prototype = Animal;  //I'm assuming this does not inherit

alert(Rabbit.prototype.eats); // returns undefined
什么是正确的方法?

这是“答案”,但请允许我为后代提供另一种选择

调用父级的构造函数来获取父级的原型不是一个好主意。这样做可能有副作用;设置ID,跟踪实例的数量,不管构造函数内部发生了什么

您可以在子构造函数和Object.create或polyfill中使用Parent.call()来获取其原型:

function Animal () {
    this.eats = true;
}

function Rabbit (legs) {
    Animal.call(this);
    this.jumps = true;
}
Rabbit.prototype = Object.create(Animal.prototype);

// Or if you're not working with ES5 (this function not optimized for re-use):
Rabbit.prototype = (function () {
                        function F () {};
                        F.prototype = Animal.prototype;
                        return new F();
                    }());

var bugs = new Rabbit();
alert(bugs instanceof Animal); // true
alert(bugs.eats); // true
这是“回答”,但请允许我为后代提供另一种选择

调用父级的构造函数来获取父级的原型不是一个好主意。这样做可能有副作用;设置ID,跟踪实例的数量,不管构造函数内部发生了什么

您可以在子构造函数和Object.create或polyfill中使用Parent.call()来获取其原型:

function Animal () {
    this.eats = true;
}

function Rabbit (legs) {
    Animal.call(this);
    this.jumps = true;
}
Rabbit.prototype = Object.create(Animal.prototype);

// Or if you're not working with ES5 (this function not optimized for re-use):
Rabbit.prototype = (function () {
                        function F () {};
                        F.prototype = Animal.prototype;
                        return new F();
                    }());

var bugs = new Rabbit();
alert(bugs instanceof Animal); // true
alert(bugs.eats); // true