在原型中声明方法时,Javascript设置基础对象

时间:2017-07-02 17:00:13

标签: javascript inheritance prototype

我读到在原型中声明对象方法是一种很好的方法,因为它可以节省内存并允许在任何时候为所有对象更改实现。 但是当我需要为使用原型方法声明的对象设置基础对象时我需要做什么? 例如:

function Animal() {
   this.age = 0;
   this.weight = 0;
   //other properties
}

Animal.prototype = {
   //some methods for Animal
}


function Dog() {
   //properties for Dog
}

Dog.prototype = {
   //some methods for Dog
}

那么,我怎样才能将Animal设置为Dog的基类(对象)(因为Dog中的prototype属性被实现为方法的自定义对象)?

2 个答案:

答案 0 :(得分:3)

ES5版(仍然最常见,但我不推荐它 - 请参阅ES6版本)

根据这篇文章here,你需要像这样使用Object.create:

function Animal() {}
Animal.prototype = {};

function Dog() {}
Dog.prototype = Object.create( Animal.prototype );

另请参阅此解决方案Object.assign(遗憾的是IE不支持)

ES6版本

class Animal {
  // all your methods come in here. No more prototype needed.
}

class Dog extends Animal {

}

即使大多数浏览器尚未完全支持ES6,您仍然可以使用ES6。使用babel来转换JS。

答案 1 :(得分:1)

您可以将Animal定义为函数,并使用其构造函数在Dog原型中设置它的实例:

Dog.prototype = new Animal();    

更完整的代码:

var Animal = function () {    
   this.age = 0;
   this.weight = 0;

    this.age = function () {
        return this.age;
    }
    // define other methods ...    
    // ...
    return this;
};

var Dog = function () {           
    // overriding the age 
    this.age= 10;    
    // define or override methods ...    
    // ...
    return this;
};

// Dog extends animal
Dog.prototype = new Animal();    

// Creating an instance of Dog.
var dog = new Dog();
相关问题