I have an animal object , and I want to create a dog object and it inherit from animal.
the following code is ok:
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
but I want to implement the Object.beget function like this:
if (typeof Object.beget !== 'function') {
Object.beget = function (o) {
var F = {};
F.prototype = o;
return F;
}
}
create an empty object,and change it`s prototype object to animal object, but it is error:
Uncaught TypeError: dog.voice is not a function
Can anyone tell me where I am wrong? thank you very much!