我有一个动物对象,我想创建一个狗对象,它继承自动物。
下面的代码就可以了:
var animal = {
name: "animal",
voice: function () {
return 'haha';
}
};
if (typeof Object.beget !== 'function') {
Object.beget = function (o) {
var F = function () {};
F.prototype = o;
return new F();
}
}
var dog = Object.beget(animal);
dog.voice = function () {
return 'wangwang';
};
document.writeln(dog.name);
document.writeln(dog.voice());
// animal
// wangwang
但我想实现 Object.beget 函数,如下所示:
if (typeof Object.beget !== 'function') {
Object.beget = function (o) {
var F = {};
F.prototype = o;
return F;
}
}
创建一个空对象,并将其原型(prototype)对象改为动物对象,但报错:
Uncaught TypeError: dog.voice is not a function
谁能告诉我哪里错了?非常感谢!
最佳答案
您需要Object.create
,它将创建一个新对象,其原型(prototype)是作为第一个参数传递的对象:
var animal = {
name: "animal",
voice: function () {
return 'haha';
}
};
if (typeof Object.beget !== 'function') {
Object.beget = (o) => Object.create(o);
}
var dog = Object.beget(animal);
dog.voice = function () {
return 'wangwang';
};
document.writeln(dog.name);
document.writeln(dog.voice());
// animal
// wangwang
另一个选择是使用 setPrototypeOf
,它将通过分配给 F
的 prototype
属性来完成您尝试执行的操作。但是,分配给 prototype
属性仅对构造函数(或类
)有意义 - 如果您有一个对象> (而不是构造函数)您想要设置其原型(prototype),请使用setPrototypeOf
。 (分配给 __proto__
属性也可以,但 setPrototypeOf
更好)
var animal = {
name: "animal",
voice: function () {
return 'haha';
}
};
if (typeof Object.beget !== 'function') {
Object.beget = function (o) {
var F = {};
Object.setPrototypeOf(F, o);
return F;
}
}
var dog = Object.beget(animal);
dog.voice = function () {
return 'wangwang';
};
document.writeln(dog.name);
document.writeln(dog.voice());
// animal
// wangwang
但是改变内置对象(例如 Object
)是非常糟糕的做法 - 如果可能的话,请考虑其他解决方案。
关于javascript - 如何在JavaScript中创建继承现有对象的新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50637902/