在下面的代码中,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).我在做什么/理解不正确?
更新:与上述内容一致,如果我执行以下操作...
Fruit.prototype = {
hello: "World"
};
Run Code Online (Sandbox Code Playgroud)
...而不是我在上面的例子中做的,我得到Object()了对象的构造函数,即使我用它创建它new Fruit().
为什么对象的构造函数属性包含用于构建它的谱系中最旧的函数而不是最新的函数?
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() 函数作为构造函数。这也会传递给用它构造的所有对象。