Benefits of using `Object.create` for inheritance

前端 未结 4 1180
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 05:43

I\'ve been trying to wrap my head around the new Object.create method which was introduced in ECMAScript 5.

Usually when I want to use inheritance I do

4条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 06:20

    First, running the Animal constructor may have undesired side effects. Consider this:

    var Animal = function(name) {
        this.name = name;
        Animal.instances.push(this);
    };
    Animal.instances = [];
    

    This version would keep track of all instances that have been created. You don't want your Dog.prototype to be recorded there.

    Second, Dog.prototype = Animal.prototype is a bad idea, since that would mean that bark would become a method of Animal.

提交回复
热议问题