为什么对象的构造函数对应于父的构造函数?

Sid*_*rth 5 javascript

在下面的代码中,orange构造函数记录为其父的构造函数(Plant()),而不是它的构造函数Fruit().为什么会这样?

(对不起有关随机对象.这是半夜,我只是在学习一些JavaScript.在现实世界中没有想太多关于它们的意义,只需将它们作为样本输入就能更好地理解原型.)

function Plant(name, colour) {
    this.name = name;
    this.colour = colour;
}

Plant.prototype.print = function () {
    return "I'm a " + this.name.toLowerCase() + " and I'm " + this.colour.toLowerCase() + ".";
}

var mango = new Plant("Mango", "Orange");
console.log(mango.constructor);

function Fruit(type, isOrganic) {
    this.type = type;
    this.isOrganic = isOrganic;
}
Fruit.prototype = new Plant("Orange", "Orange");

var orange = new Fruit("staples", true);
console.log(orange.constructor);
Run Code Online (Sandbox Code Playgroud)

我得到了Plant(name, colour)两个console.log()调用,而我认为我应该为第二个调用Fruit(type,isOrganic).我在做什么/理解不正确?

http://jsfiddle.net/eHZf8/

更新:与上述内容一致,如果我执行以下操作...

Fruit.prototype = {
    hello: "World"
};
Run Code Online (Sandbox Code Playgroud)

...而不是我在上面的例子中做的,我得到Object()了对象的构造函数,即使我用它创建它new Fruit().

为什么对象的构造函数属性包含用于构建它的谱系中最旧的函数而不是最新的函数?

Mat*_*ing 4

JS 是一种基于原型的语言。对象不是由面向对象语言创建的,其行为也与面向对象语言中的不完全相同。

这意味着当您致电...

Fruit.prototype = new Plant("Orange", "Orange");
Run Code Online (Sandbox Code Playgroud)

您定义的水果“类”(尽管没有类)与名称=>“橙色”且颜色=>“橙色”的植物完全相同。一切都被复制,包括构造函数。

除了现在所有水果都是橙子的问题之外,解决这个问题的一种方法是包括这一行......

function Fruit(type, isOrganic) {
    this.type = type;
    this.isOrganic = isOrganic;
}
Fruit.prototype = new Plant("Orange", "Orange");
Fruit.prototype.constructor = Fruit; // <--- Add this
Run Code Online (Sandbox Code Playgroud)

这使得 Fruit 使用 Fruit() 函数作为构造函数。这也会传递给用它构造的所有对象。

  • 从 OOP 的角度来看,这似乎有些黑客行为。但在基于原型的语言中,不存在真正的“继承”。我们不能说Fruit是Plant的“子类”,我们必须说Fruit与Plant完全相同,然后添加一些差异使其独一无二。构造函数就是这样的区别之一,因为 Fruit 需要自己的构造函数。为了进一步参考,这种方式是 Mozilla 在[教程](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance)中推荐的一种方式。 (2认同)