0

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!

Kunj
  • 1,980
  • 2
  • 22
  • 34
shengbin_xu
  • 128
  • 3
  • 14

1 Answers1

1

You want Object.create, which will create a new object whose prototype is the object passed as the first parameter:

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

Another option is to use setPrototypeOf, which will do what you were trying to do by assigning to F's prototype property. But assigning to the prototype property is only meaningful for a constructor function (or class) - if you have an object (rather than a constructor) whose prototype you want to set, use setPrototypeOf instead. (assigning to the __proto__ property can work too, but setPrototypeOf is better)

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

But mutating the built-in objects like Object is very bad practice - consider another solution if at all possible.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320