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

标签 javascript inheritance prototype

我读到,在原型(prototype)中声明对象方法是一种很好的方法,因为它可以节省内存并允许随时更改所有对象的实现。 但是,当我需要为使用原型(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)属性是作为方法的自定义对象实现的)?

最佳答案

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,尽管大多数浏览器尚不完全支持它。使用babel转译你的 JS。

关于Javascript在原型(prototype)中声明方法时设置基础对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44873190/

相关文章:

javascript - 使用 setInterval 为 jQuery 淡入和淡出更新数组

javascript - 第二次单击时 jQuery 对话框未打开

javascript - JQuery - 页面不重新加载

java - 从 Java 中的基类访问子类字段

C++单例模板类继承

javascript - 有底部限制的粘性左侧部分

java - 如何使用 iBatis for Java 实现继承?

Javascript 原型(prototype)什么是正确的?

javascript - 在 jQuery 方法中使用 this

javascript - 对于原型(prototype) ajax,使用上下文相当于什么?